dot
dot

Reputation: 15670

how to find form closest a button with a specific text value

I have a web page that has multiple forms. I'm trying to locate the form that has a "Add" button inside of it, and then assign an id to the form. Then I need to find an element within this named form... an input element, and assign a value to it.

so for example, i have the following test HTML:

<H1>Add A Call Route</H1><DL>
<form action="myapp/controller/addcallroute" method="POST">

<input class=" text" type="text"  name="contact_details"  value=""  id="contact_details" >

<input class=" hidden" type="hidden"  name="rule_id"  value=""  id="rule_id" >


<input class="submit" type="submit" name="submit" value="Add">

</FORM>

Here's the code I am trying to use to find the right form.. and assign an id to it:

    var $callroute_form = $(":contains('Add')").closest("form");
    $callroute_form.attr('id',"callroute_form");        

When I debug in the console and try to see what the value of $("#callroute_form") is, I just get "[]".

ultimately, what I need to do is assign a value to the "rule_id" field. But I have multiple rule_id fields in multiple forms... Alternatively, I guess I good try to look for the "Add" button, and populate the "rule_id" that's closest to it..?

thanks.

Upvotes: 1

Views: 253

Answers (3)

Andy
Andy

Reputation: 3012

To find the form by the way you explained and add an id to it:

// first method:
$('input[value="Add"]').parent().attr('id',"callroute_form");

// second method:
$('input[value="Add"]').closest('form').attr('id',"callroute_form");

To find elements in this form and edit the value:

$('#callroute_form').find('input[name"rule_id"]').val('newvalue');

Upvotes: 1

Rakesh Juyal
Rakesh Juyal

Reputation: 36779

Pick all forms and filter the form on the basis of the input button. Now, do whatever you want to do with the form.

$('form').filter( function() {
  return $(this).find("input[value='Add']").length == 1;
}).attr('id', 'callroute_form' )';

Upvotes: 0

Itay
Itay

Reputation: 16785

The :contains selector doesn't fit here because it searches for an element inner text, not value.

Try the Attribute Equals Selector

var $callroute_form = $("input[value='Add']").closest("form");

From the :contains documentation:

contains selector

Description: Select all elements that contain the specified text.

Upvotes: 2

Related Questions