target input by type and name (selector)

Jquery

Jquery Problem Overview


I need to change some checkbox inputs to hidden inputs for some but not all inputs on a page.

<input type="checkbox" name="ProductCode"value="396P4"> 
<input type="checkbox" name="ProductCode"value="401P4"> 
<input type="checkbox" name="ProductCode"value="F460129">

The jquery code below only selects the input by type which causes all check boxes to changed to hidden inputs Is there a way to check for both type of input="checkbox" and name="ProductCode" as the selector so I can specifically target those that I want to change?

$("input[type='checkbox']").each(function(){
var name = $(this).attr('name'); // grab name of original
var value = $(this).attr('value'); // grab value of original
var html = '<input type="hidden" name="'+name+'" value="'+value+'" />';
$(this).after(html).remove(); // add new, then remove original input
});

Jquery Solutions


Solution 1 - Jquery

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

Solution 2 - Jquery

You can combine attribute selectors this way:

$("[attr1=val][attr2=val]")...

so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]. jQuery has a selector for that, namely :checkbox so the end result is:

$("input:checkbox[name=ProductCode]")...

Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:

<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">

allowing you to use the much faster selector of:

$("input.ProductCode")...

Solution 3 - Jquery

input[type='checkbox', name='ProductCode']

That's the CSS way and I'm almost sure it will work in jQuery.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser357034View Question on Stackoverflow
Solution 1 - JqueryRuss CamView Answer on Stackoverflow
Solution 2 - JquerycletusView Answer on Stackoverflow
Solution 3 - JqueryDaniView Answer on Stackoverflow