dot
dot

Reputation: 15670

find an button and assign an id via jquery / javascript

I have a web page that includes two forms... both within a <DL>

<dl>
<form action="" method="POST" style="display:inline-block;">
    <dl><dt></dt><dd><input class="submit" type="submit" value="Create TEST" style="width: 15em;"></dd></dl>
</form>
<form action="" method="POST" style="display:inline-block;">
    <dl><dt></dt><dd><input class="submit" type="submit" value="Create TEST2" style="width: 15em;"></dd></dl>
</form>    
</dl>

I need to find both buttons and assign ids to them.

Here's what I have so far:

//find the two create buttons and assign ids
$('body FORM:contains("Create TEST")').contents().each(function () {
var exp = /Create TEST/;        
if (this.nodeValue && exp.test(this.nodeValue)) {                      
    var $createoutrule = this;
    $createoutrule.attr('id',"id123");
    return 
}; 
}); 

But it's not working... can you tell me what I'm doing wrong? I'm going to google .contents() to make sure I understand how / what it should be returning...

Thanks.

Upvotes: 1

Views: 105

Answers (3)

Anand Jha
Anand Jha

Reputation: 10724

Try This,

$('input[type="submit"]').each(function () {
          var exp = /Create TEST/;   

           if (exp.test(this.value)) {                      

                     $(this).attr('id',"id123");//put diffrent id because id should be unique
                     return ;
           }; 
});

Working Demo

Upvotes: 0

kaushik0033
kaushik0033

Reputation: 677

You can get all submit type button on forms using $( " :submit ").functionname()

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075467

:contains looks for textual content.

Your selector can be much simpler:

$('input[type=submit][value^="Create TEST"]')...

...which means "an input with type "submit" whose value attribute starts with "Create TEST"".

To add id values to them (note that they must be two different id values, because ids must be unique on the page), then:

$('input[type=submit][value^="Create TEST"]').each(function(index) {
    this.id = "id" + index; // Will be "id0" then "id1"
});

Of course, as you already have the buttons using the above code, you may not need to assign id values to them anymore, you can just do whatever you were going to do with them later using ids right away in the code above. But if your use-case requires ids, the above'll do it.


If those values are just placeholders, the same general principal applies: If the both start with the same text, you can use the attribute-starts-with selector above; if not, there's also the attribute-ends-with selector, the attribute-contains selector, ...

Upvotes: 5

Related Questions