1

my html code:

<li id='category-10'>
<label class="selectit">
<input value="10" type="checkbox" name="post_category[]" id="in-category-10" /> Developmental
</label>
</li>

my javascript code:

function onCategoryClick() {
 $(".selectit").click(function(e){
    var categoryValue = $(e.target).text();
    alert("The value is " + categoryValue);
 });
}

This returns me the string "The value is Developmental" but what I want is "The value is 10" I'm new to Javascript, how would I go about targeting the value field in the input, instead of the text?

I've also tried

var categoryValue = $(e.target > input).value;

But this doesn't return anything.

0

1 Answer 1

1

Instead of

$(e.target).text();

try

$(this).find('#in-category-10').val();

Here e.target corresponds to the label . And it has text 'Developmental' and also a nested input element. So you need to use find to access it. (If there is no id)

But ID is supposed to be unique on the page. So to access the element you can directly used the id selector

var categoryValue = $('#in-category-10').val();

And remember that input has no text property. Need to use the val method

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

3 Comments

Thanks @Sushanth! Using .val(); did the trick! However the reason i'm using $(e.target) is because I have many list items with different id's, <li id='category-1'>, <li id='category-2'> <li id='category-3'> etc. I want to write one script that handles them all, regardless of which checkbox you click, it will return saying "The value is .." and then whatever the value of that checkbox is.
@crusarovid.. Glad to have helped :)
You can avoid use this instead e.target .. This should be good enough $(".selectit").click(function(e){ var categoryValue = $(this).find('input').val(); alert("The value is " + categoryValue); }); .. This will work for the markup that you were referring to

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.