Same id with diffent classname in html and javascript - javascript

I have a situation where
<label id="studentName" class="firstClass> </label>
<label id="studentName" class="secondClass> </label>
<label id="registerNumber" class="firstClass> </label>
<label id="registerNumber" class="secondClass> </label>
Now, I have to identify each tag uniquely and replace the innerHTML with some value, using class and id.
How Can I achieve this from javascript/ios side ?

You want to switch the Id and classes around. You CANT have 2 of the same ID's But you can have multible Classes with the same name.
<label id="firststudentName" class="studentName> </label>
<label id="secondstudentName" class="studentName> </label>
<label id="firstregisterNumber" class="registerNumber> </label>
<label id="secondregisterNumber" class="registerNumber> </label>

You can use
elements = document.getElementsByClassName(names);
and loop on the results, there is also hasClass function.
But normally an ID should be unique.

try this with jquery:
function checkUnique(className){
var count = 0;
var ids = '';
$('.' + className).each(function(i){
if(ids.indexOf($(this).attr('id')) != -1){
$(this).attr('id',$(this).attr('id') + i);
}
ids += $(this).attr('id');
})
}

This is invalid HTML, see here: http://www.w3schools.com/tags/att_global_id.asp
If you're iterating through e.g. a number of students, make sure to use the cycle for the id so you have
id="studentName1"
id="studentName2"

Related

Get the id of input using it's name

I want to get the id of input using it's name,and to empty the input field.But it's not working.Is it possible?
html:
<input type="text" id="1" name="Color" maxlength="2" />
jQuery:
var myId="#";
myId=myId + $('[name="Color"]').attr('id');
$($myId).var('');
You can do this:
let id = $('input[name$="Color"]').val('').attr('id');
console.log(id);
$(`#${id}`).val('');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="1" name="Color" maxlength="2" />
You can set the input value using the val() function.
<input type="text" id="1" name="Color" maxlength="2"/>
var myId='#' + $('[name="Color"]').attr('id');
$(myId).val('');
To get the input value use it like this:
$(myId).val();
Try this code.
const myId = $('input[name="Color"]').attr('id');
$("#"+myId).val(''); // you can set any value here or you can perform any other operations on this element -> $("#"+myId)
On first line of this JS code, we are getting id attribute and then on second line, we're using to manipulate element.
Now, if you want id only for performing some operations on that input element, you don't need to get id. You can also do like this.
let elem = $('input[name="Color"]');
elem.val(''); // only if same name is not used anywhere else.
I hope this helps you.
You can use attr directly to set a value. Moreover there is no need to append #.
let element = $('[name="Color"]');
console.log("before", element.attr('id'));
element.attr('id', null);
console.log("after", element.attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="1" name="Color" maxlength="2" />

Is there a JS/jQuery function that takes the ids of every element with a certain class?

I have 4 html input elements:
<input type="checkbox" class="viewButton" id="html-button">
<input type="checkbox" class="viewButton" id="css-button">
<input type="checkbox" class="viewButton" id="javascript-button">
<input type="checkbox" class="viewButton" id="output-button">
What I'd like to do is get the name of each id in every element with a class of "viewButton" and put them in an array.
In order to do that, I wrote this:
var viewButtonsArray = [];
viewButtonsArray.push($(".viewButton"));
var buttonIdsArray = [];
for (var i = 0; i < viewButtonsArray[0].length; i++) {
buttonIdsArray.push(viewButtonsArray[0][i].id);
}
The code works. However, I was wondering if there was an easier way to do this.
Thanks!
(I don't think this is a duplicate. The link being claimed as a duplicate solves a problem regarding an element within another element, the parent has the class, child has the id. My question is about elements with BOTH a class and id, hence the title "ids of every element with a certain class" and not "id of elements within a parent element with a class".)
You can do this with map() and get() DEMO
var viewButtonsArray = $('.viewButton').map(function() {
return $(this).attr('id');
}).get();
console.log(viewButtonsArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="viewButton" id="html-button">
<input type="checkbox" class="viewButton" id="css-button">
<input type="checkbox" class="viewButton" id="javascript-button">
<input type="checkbox" class="viewButton" id="output-button">
You could use:
var ary = [];
$('.viewButton').each(function(){ ary.push(this.id) })

How can I change the index of input element dynamically based on parent and inner parent in jquery

How can I change the index of input element dynamically based on the parent and inner parent count in jQuery.
In the following code how can I change the index of form elements
<div id='parent_container0'>
<div id='parent_inner_container0'>
<label> Name </label>
<input type='text' name='name[]'/>
<div id='child_container0'>
<div id='child_inner_container0'>
<label> Email </label>
<input type='text' name='email[]'/>
<label> Phone </label>
<input type='text' name='phone[]'/>
</div>
</div>
</div>
</div>
<div id='parent_container1'>
<div id='parent_inner_container1'>
<label> Name </label>
<input type='text' name='name[]'/>
<div id='child_container1'>
<div id='child_inner_container1'>
<label> Email </label>
<input type='text' name='email[]'/>
<label> Phone </label>
<input type='text' name='phone[]'/>
</div>
</div>
</div>
</div>
I need the changed name of form element as
name[0]
email[0][0]
phone[0][0]
name[1]
email[1][0]
phone[1][0]
Based on the parent's index of those elements in jQuery.
How can I achieve this?
Any help is appreciated.
Thanks,
Note: The requirement is to use a nested form to add more form of parent and Child with each form has nested form fields I am using the following code for changing index.
$('.parent_container').each(function(i) {
var pindex = $(this).index();
var mainfrm=$(this);
var orgname="";
mainfrm.find('.parent_container_inner').each(function(j) {
$(this).find('input, select, textarea').each(function(k){
orgname = $(this).attr('name');
orgname = orgname.replace(/[[]\d]+/g,"");
$(this).attr('name', orgname+"["+pindex+"]["+j+"]["+k+"]");
});
});
});
First, you should select your parent "containers" with:
$("div[id^=parent_container]").each(function(){
console.log(this);
});
It will print your two parent_container (parent_container0 and parent_container1). Check out here how to use selector attribute with Starts With
Then you will need to find and replace all name[], email[] and phone[].
So, you should use Ends With, to find each input you need to replace the name
$("div[id^=parent_container]").each(function(){
var parentContainerId = this.id.replace('parent_container', '');
$(this).find("input[name$='[]']").each(function(){
var newName = this.name.replace('[]', '[' + parentContainerId + ']');
this.name = newName;
})
});
Here is the Fiddle
Also, concerning your question, you should definitely take a better look into JQuery Selectors

How to select all elements in name array?

I am trying to sum a collection of radio selections using jQuery.
<input name="cost[alpha]" type="radio" >
<input name="cost[beta]" type="radio">
<input name="cost[delta]" type="radio">
...
$('input[name="cost[*]"]').each( function() {
...
}
This does not function as it tries to resolve an input with the name "cost[*]". Ideally I would like to iterate over any element in the cost array. Is there a preferred way of doing this with jQuery? I have other elements in my form that use the radio type so selecting radios in general is not a valid option.
Make the attribute selector the "starts with" selector (^=):
$('input[name^="cost"]').each(function() {
...
});
If you find that you have other input elements that start with "cost" or even "cost[", then perhaps you want to think about changing the way you're querying for the elements. One alternative would be adding a special class name to the elements you're targeting and forget about their names altogether. For example:
<input name="cost[alpha]" type="radio" class="form-cost">
<input name="cost[beta]" type="radio" class="form-cost">
<input name="cost[delta]" type="radio" class="form-cost">
And then your selector is very simple and very targeted:
$('input.form-cost').each(function() {
...
});
You might get the best performance out of simply wrapping the elements in a container with a unique id or class name, and querying for input elements that it contains (as suggested by Allende in the comments):
<div id="cost-inputs">
<input name="cost[alpha]" type="radio">
<input name="cost[beta]" type="radio">
<input name="cost[delta]" type="radio">
</div>
$('#cost-inputs input').each(function() {
...
});
Try with contains selector in jquery
$("input[name*='cost[']").each(function(){});
Try:
var sum = 0;
$("input[name^='cost']").each(function() {
sum += Number($(this).val());
});
About "Starts With Selector": [name^="value"]
https://api.jquery.com/attribute-starts-with-selector/

jQuery find() returns only the first matched result ?

I am using the $.find() method in jQuery and i am not able to get all the results which match the selector condition.
This is my HTML
<div class="something">
<label> Hello </label>
<div class="selse">
<label> Hi </label>
<label class="imp"> This is </label>
<label class="imp"> Nooo </label>
</div>
<label class="imp"> Sparta </label>
<label class="imp"> Right ? </label>
</div>
<div class="something">
<label> Hell No </label>
<div class="selse">
<label> Hi </label>
<label class="imp"> Cant </label>
</div>
<label class="imp"> touch </label>
<label class="imp"> this </label>
<label class="imp"> MC </label>
</div>​
So when i do the following JS
$("div.something").each(function(index) {
alert(index + ': ' + $(this).find("label.imp").html())
});​
I expected that it'll give me 2 alerts . One with 0. This is, Nooo, Sparta, Right ? and the other with 1. Cant, touch, this, MC . But i got just 0. This is and 1. Cant .
I tried using arrays in the same function like this
$("div.something").each(function(index) {
var arr=[]
arr = $(this).find("label.cidForm").html();
alert(arr);
});​
No i get alert boxes with 'Undefined' in them. What am i doing wrong in both these cases ? I just want an array with all the values inside label.imp elements.
Here's a JSFiddle i put up for the same. http://jsfiddle.net/WPeKF/1/
.html() and other getter methods only return the value of the first matched element. With that in mind, i think you can figure out the logic changes that need to be made.
Fiddle: http://jsfiddle.net/WPeKF/2/
Code:
var arr = $("div.something").map(function(){
return $(this).find("label.imp").map(function(){
return $(this).html();
}).get().join("");
}).get();
console.log(arr);
This should do the trick:
var myArray = $("div.something label.imp").map(function(index) {
return $(this).html();
});​

Categories