Matt Aikens
Matt Aikens

Reputation: 86

Programmatically Setting Number Input Value Not Working

I have a piece of javascript that sets the number input value. However, it won't work. The input's value field is still empty after the call (although console.log() outputing the element's val() does show the correct value). I have tried setting the value three ways jQuery's .val(total), .attr('value', total), and with plain old .value =, and still nothing. I even replaced the entire element with html and the value concatenated into the value attribute, and it won't work.

Any ideas why this won't take?

Here's the markup:

<div id="proposal_price_box">
  <div class="proposal_price_header sys_bkgcolor">
    <span class="title"><h3>Price to Appear on Proposal</h3></span>
  </div>
  <div class="inner">
    <span class="label">$</span>
    <input type="number" class="amount-input" id="proposal_price" value=""/>
  </div>
</div>

And the pertinent javascript:

$('#proposal_price').val('1234');

Jsfiddle demonstrating the problem below.

http://jsfiddle.net/n8z9K/12/

Somehow, if the element's container is displayed, it will set the value. But as soon as its hidden again, it breaks.

EDIT Sorry, I didn't properly demonstrate the problem in JSfiddle. I am trying to clone the contents of the container and place it elsewhere. I've updated the jsfiddle to better show the issue.

Upvotes: 1

Views: 3104

Answers (2)

marty
marty

Reputation: 4015

There is a difference between an input node's value and its value attribute. When you assign its value with the val() method, you're setting its value, not its value attribute. When you use the html() method you are getting the html with all attributes (including the value attribute), but that attribute has not changed thru your val() assignment. Only the node's value has changed.

Upvotes: 2

11684
11684

Reputation: 7507

You do #proposal_price { display: none; }. If you that element, it keeps the same ID (that is actually invalid, but modern browser can handle this). Thus, it remains hidden because of the display: none; you should remove the ID of the clone, otherwise the clone won't be displayed either.

Yep, this jQuery seems to solve it:

$(document).ready(function() {
    $('#proposal_price').val('123');
    console.log("before clone");
    clone = $('#proposal_container').clone();
    clone.attr("id", "");
    console.log("after clone");
    $('body').append(clone.html());
});

Upvotes: 0

Related Questions