0

I want to change the value of a text input with jQuery when a certain function passes. I used this code:

$('#find').attr("value", "newvalue");

But it's not changing it. This is the markup of the input I want to change:

<input type="text" id="find" class="input" />

I know it's getting to this peice of code because the jQuery either side of it executes and works.

Any help would be appreciated, thanks.

1
  • I put your code here: jsbin.com/omoda3 (view the source). It works fine. You're doing something else wrong. Commented Dec 5, 2009 at 21:39

4 Answers 4

7
$("#find").val("newvalue");

Not sure why yours doesn't work though. You might also need a name attribute on the input? Not sure if that matters...

It could also be running before the input is created. In which case wrap it in

$(document).ready(function(){
    //anything you want to do once the elements are all there.
});

Or just stick the script block after the element in your source (this might be a controversial suggestion).

5
  • Make sure the code runs after the element is created. When does this code run?
    – Adam A
    Commented Dec 5, 2009 at 20:59
  • 1
    The code runs when you click a button below the feild I want to change, so I know the element has been created. Everything is between $(document).ready anyway.
    – Joseph
    Commented Dec 5, 2009 at 21:01
  • Nothing in the code looks wrong to me, so unless I'm overlooking something the problem is elsewhere on the page. Do you have a link or anything so I can see the whole page? does something else on the page have the same id?
    – Adam A
    Commented Dec 5, 2009 at 21:05
  • Seeing the context that the js is called in could help too.
    – Adam A
    Commented Dec 5, 2009 at 21:09
  • make sure you dont have duplicate ids
    – Sharky
    Commented Mar 7, 2014 at 17:16
4

You would need to change the element's prop value.

$('#find').prop("value", "newvalue");

attr: holds the value the element had during page load

prop: holds the value of the element dynamically...the current state

http://api.jquery.com/prop/

1
  • Yes...I do realize this is a very old post. However, I havent seen an answer provided as of yet. Thought this might keep someone from plucking their hair out :)
    – ObiJuan
    Commented Oct 23, 2017 at 5:00
1

Try to use $('#find').val('newvalue');

0

Your code should work fine, are you sure your selector is doing the right thing?

As a simple test try this:

$("#find").css({'background-color' : 'yellow'});

If the selector is right then the background item will go yellow.

Also, are you sure the code is being hit, there might be an error before hitting code, try sticking a breakpoint on the line of code and make sure it gets hit.

Not the answer you're looking for? Browse other questions tagged or ask your own question.