Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Selecting the first child with a specific attribute

I have a form in HTML with multiple inputs of type submit:

<form id = "myForm1" action="doSomethingImportant/10" class="postLink" method="post">
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
<input type="submit" value="clickThisLink"></input>
<input type="submit" value="Don'tclickThisLink"></input>
</form>

What I want to do is select only the first input with type submit while ignoring the others, the snippet of code I currently have is as follows, note it is within a for-each loop that goes through all forms on my page, hence (this) to avoid confusion:

var name = $(this).find("input[type='submit']").val();

I'm thinking this already grabs the first input of type submit by default, I'm not sure if that assumption is correct or if there's a more formal way of going about it, thanks.

like image 778
kingrichard2005 Avatar asked Nov 19 '09 21:11

kingrichard2005


People also ask

Which selector select the first element of the tag in jQuery?

The :first selector selects the first element.

What is first child in jQuery?

version added: 1.1. 4jQuery( ":first-child" ) first() matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1) .

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.

Which selects elements that have the specified attribute with a value beginning exactly with a given string?

attributeStartsWith selector Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.


2 Answers

Try:

$(this).children("input[type='submit']:first").val();
like image 120
eKek0 Avatar answered Sep 23 '22 13:09

eKek0


how about the first selector

var name = $("input[type='submit']:first").val();
like image 29
Marek Karbarz Avatar answered Sep 22 '22 13:09

Marek Karbarz