0

I'm trying to check if a textfield exists withing another element, and I want to set its value if it does; otherwise, I want to add a radio. I've got the following code, but it's not working.

$("ul").each(function(){
if ( !($(this).find('input[value="9999"]').val()) ) {
    var textfield = $(this).find('input[type="text"]');
    if ( textfield.length ) textfield.value="9999";
    // ^ this doesn't work. have also tried if ($(textfield).val())
    else $(this).append('<input name="'+name+'" type="radio" value="9999" checked="checked" />');
    // ^ this works
} // if
});

btw, name is set dynamically earlier in the script.

Answer:

$("ul").each(function(){
if ( !($(this).find('input[value="9999"]').val()) ) {
    var txtfield = $(this).find('input[type="text"]');
    if ( txtfield.length ) $(txtfield).val("9999");
    // just changed this ^ line (above)
    else $(this).append('<input name="'+name+'" type="radio" value="9999" checked="checked" />');
} // if
});
3
  • 2
    did you try setting the value of the text field as $(textfield).val("9999")? Commented Jan 17, 2012 at 23:07
  • <input type="text" name="foo" /> or <input type="radio" name="foo" value="bar" /> Commented Jan 18, 2012 at 17:15
  • thanks @Anurag. since you were first, wanna put it as an answer and i'll mark it? Commented Jan 18, 2012 at 17:25

2 Answers 2

1

textfield is a jquery object already so you will need to set the value by using textfield.val("9999")

Sign up to request clarification or add additional context in comments.

Comments

0

.find() will also return a list of elements, so if there are more than one, this may not work. You may need to do another .each() on the textfield variable.

1 Comment

hmm…I would have expected the textfield.value="9999" to execute on the first element from the find if that were the case, but I'll try the .each().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.