Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: replace inputs with spans

Tags:

jquery

I'm trying to replace inputs with spans containing the input values in such a way as to be able to switch them back upon clicking a button. I figure this would be most easily done in two stages - adding <span>[input value]</span> in front of the inputs, and then hiding the inputs. The only problem is I'm having trouble with the first part. I'm trying things like

$('#container').find('input')
    .parent()
    .prepend('<span></span>') // this effectively creates: <span></span><input value=____>

However, inside the prepend statement $(this) seems to be undefined, so I can't do

    .prepend('<span>'+$(this).children('input').val()+'</span>')

Since there are several inputs, I can't simply put the input value into a variable. How would I do this?

like image 519
Mala Avatar asked Jun 29 '10 17:06

Mala


2 Answers

For the updated question:

You can do something like this (basing this on comments, an edit per row):

$('input', context).each(function() {
  $("<span />", { text: this.value, "class":"view" }).insertAfter(this);
  $(this).hide();
});

You can view a more detailed demo here, with per-row edit toggling.


For the original question:

You'll want to use .replaceWith() for this:

$('#container').find('input').each(function() {
  $(this).replaceWith("<span>" + this.value + "</span>");
});

The .each() creates a closure in which this refers to the input element, so you can use this.value for example.

To make sure encoding is taken care of, expand it a bit to use .text(), like this:

$('#container').find('input').each(function() {
  $(this).replaceWith($("<span />").text(this.value));
});​

You can try a demo here

like image 94
Nick Craver Avatar answered Oct 18 '22 09:10

Nick Craver


Seems to me like the easiest solution would be to change the inputs to readonly and remove the border (and possibly change background color, depending on your UI), which essentially makes them appear as a regular <span> label.

function spanify() {
  $('#container input')
    .attr("readonly", "readonly")
    .css("borderWidth", "0");
}

function despanify() {
  $('#container input')
    .removeAttr("readonly")
    .css("borderWidth", "auto");
}

Is that feasible?

like image 42
Josh Stodola Avatar answered Oct 18 '22 08:10

Josh Stodola