0

So here is my code. I am trying to set the value of a hidden form input.

if($gender == "BOY" || $gender == "MALE" || $gender == "M" || $gender == "1") {
        console.log('Its a boy!');
        $(".girlsonly").hide();
        document.getElementsByName('dressjacket')[0].placeholder='Jacket';
        $('#majorgender').val('1');
    };
    if($gender == "GIRL" || $gender == "FEMALE" || $gender == "F" || $gender == "0") {
        console.log('Its a girl!');
        document.getElementsByName('dressjacket')[0].placeholder='Dress';
        $('#majorgender').val('0');
    };

Here is the form input:

<input type="hidden" name="majorgender" id="majorgender"></input>

It successfully logs "Its a girl!" or "Its a boy!" but afterwards when I insert "alert($('majorgender').val());" it alerts "undefined"

If I log alert($('majorgender')) it replies with "object Object" so I know it exists, I just dont know why its not setting properly.

Any thoughts?

5
  • alert($('foobarBARBAR')) alerts object Object too, and obviously it doesn't exist. To test for existence, test the length property of the jquery object. alert($('foobarBARBAR').length)
    – Kevin B
    Commented Apr 18, 2013 at 18:16
  • 1
    Do you do an alert($('majorgender').val()) or an alert($('#majorgender').val())? Commented Apr 18, 2013 at 18:16
  • Do you access them after DOM is ready?
    – Adil
    Commented Apr 18, 2013 at 18:17
  • alert( $('#majorgender').attr('name') ); If this return correct value, then it exists. Else, move you jQuery code to below the <body> tag Commented Apr 18, 2013 at 18:17
  • input is a self closing tag. You don't need </input> in there
    – Kai Qing
    Commented Apr 18, 2013 at 18:18

3 Answers 3

7

You need a # in - alert($('#majorgender').val()); - otherwise it is looking for a tag called majorgender as opposed to an ID

ie. you are currently looking for <majorgender...

1
  • @Rick Bross : If this it was the most helpfull answer so please accept it otherwise accept the answer that make sense to you and solve your problem and if your problem is not solved tell us so we can help you better more :) Commented Apr 18, 2013 at 18:26
2

You are alerting the input majorgender like this $('majorgender').val() When really you need to alert it like this $('#majorgender').val()

Because you are selecting this input by id you must precede the selector name by a hash #

And note that jquery define every selector even if it is not valid as object so it is not necessary if your log show an object that means that your selector is correct and exists :)

Try and tell me if that was helpful :)

0
1

you missed # changed to

alert($('majorgender').val());

to

alert($('#majorgender').val());

Your Answer

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

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