Find all duplicate ids and add unique key - javascript

how to find all duplicate ids when the page is relaod:
Let's say we have html like this:
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
The idea is to find duplicate ids and add +1 or something like that:
What I want to achieve is:
<input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />
JS
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
$(this).attr('id', $(this).attr('id') + i);
});
Any ideas? Thank you all.

I would strongly recommend you serve valid HTML rather than manipulating Ids.
However, You are were close as attribute value selector may return multiple elements, You need to iterate the matching elements
var handled = [];
$('[id]').each(function() {
if (handled.includes(this.id)) {
return;
}
var elemets = $('[id="' + this.id + '"]');
if (elemets.length > 1) {
handled.push(elemets.attr('id'));
elemets.attr('id', function(index, v) {
return v + (index+1);
});
}
});
//For Readablity
$('[id]').each(function(){
console.log(this.outerHTML)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />

Try like this.
var allId = [];
var data = [];
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(allId.indexOf(this.id) < 0){
data[this.id] = 1;
allId.push(this.id);
} else {
data[this.id]++;
}
$(this).attr('id', $(this).attr('id') + data[this.id]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />

No need for jQuery:
const ids = {}
document.querySelectorAll('[id]').forEach(node => {
if (ids[node.id] !== undefined) {
ids[node.id] += 1
} else {
ids[node.id] = 1
}
node.id = `${node.id}${ids[node.id]}`
})
document.querySelectorAll('[id]').forEach(node => console.log(node))
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />

try this
var i = 0;
('[id]').each(function(){
var allIds = $('[id^="'+this.id+'"]').length
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
var i = allIds - ids.length + 1
$(this).attr('id', $(this).attr('id') + i++);
})

var a = [];
var i =0;
jQuery('[id]').each(function(){
if(a.indexOf(this.id) !== -1){ //checks if id exists in array
i++;
}
else{
i = 1;
a.push(this.id);
}
jQuery(this).attr('id', jQuery(this).attr('id') + i);
});
Explaination : I am storing each new id in array. At each iteration it checks whether the id is repeated, if so then the attribute is incremented to 1.

Related

Javascript error in getting values from checkboxes

I'm not able to get the value from my checkboxes when each of them is selected alone (i.e. in isolation), except for the last one which works fine.
Could anyone help me figure this out and correct my code?
function showChoices() {
var values = [];
var cbs = document.catalog.colors;
for (var i = 0, cbLen = cbs.length; i < cbLen; i++) {
if (cbs[i].checked) {
values.push(cbs[i].value);
document.getElementById('display').innerHTML = "You selected: " + values.join(', ') + ".";
} else {
document.getElementById('display').innerHTML = "Please select an option.";
}
}
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>
Working Solution
You can write js like this and hope this helps:
function showChoices() {
var values = [];
var cbs = document.catalog.colors;
var cbLen = cbs.length;
for (var i = 0; i < cbLen; i++) {
if (cbs[i].checked) {
values.push(cbs[i].value);
}
}
if (values.length != 0) {
document.getElementById('display').innerHTML = "You selected: " + values.join(', ') + ".";
} else {
document.getElementById('display').innerHTML = "Please select an option.";
}
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>
You are overriding the div#display's innerHTML with the "Please select an option..." text whenever the last iteration of your loop jumps into the else block (meaning the last box isn't checked).
I would check if at least one element is selected, and if not return early from your function. After that, you can simply display the values by joining them together.
function showChoices() {
var values = [];
var cbs = Array.from(document.catalog.colors);
let el = document.getElementById('display');
let checked = cbs.filter(e => e.checked);
if (!checked.length) {
el.innerHTML = 'Please select at least one';
return false;
}
el.innerHTML = `You selected ${checked.map(e => e.value).join(', ')}`;
return false;
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>

How to stop user for using same username which already exist in my local storage?

var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function agecal() {
var Bdate = inputsarray[4].value;
var Bday = +new Date(Bdate).getFullYear();
var age = (new Date().getFullYear() - Bday);
inputsarray[5].value = age;
}
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
} else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) users.Purpose += " Storing Apps";
if (inputsarray[9].checked === true) users.Purpose += " Storing Sites";
if (inputsarray[10].checked === true) users.Purpose += " Fun";
array.push(users);
localStorage.setItem("Users Data: ", JSON.stringify(array));
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
for (var i = 0; i < arrayobjfromls.length; i++) {
if (inputsarray[2].value === arrayobjfromls[i].UserName) {
alert("This username is already in use. Please try another.");
localStorage.removeItem(arrayobjfromls[i]);
}
}
}
<div>
<center>
<form action="javascript:void(0);" method="post" onsubmit="subm();">
<label for="fname">First Name:</label> 
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label> 
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label> 
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>  
<input type="password" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>  
<input type="date" id="dob" onchange="agecal();" />
<br/>
<label>Age:</label>     
<input type="text" id="age" disabled="disabled" />
<br/>
<span>Gender:</span>     
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>
Please help me I want to stop user for using username which already present in my local storage by showing an alert and also I don't want to send data to local storage in which username is same of that data which is already present in my local storage...so that my local storage contain only those objects which have different usernames.
You're already checking for this; you're just doing it after you've already added the new user. Do the check first:
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
var found = false;
for (var i = 0; i < arrayobjfromls.length; i++) {
if(users.UserName === arrayobjfromls[i].UserName) {
found = true;
break;
}
}
if ( found ) {
alert("This username is already in use. Please try another.");
} else {
array.push( users );
localStorage.setItem("Users Data: ", JSON.stringify(array));
}

Javascript: How to check if each input value is duplicated to another input value

So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />

getElementsByClassName and innerHTML

Can someone explain how to appendChild to a parent <div class="...">
and solve this ?
The innerHTML should set the variable str after every <div class='categories'> </div>
it created dynamically when you set a value to the texts and press the button "press"
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories');
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + "" + fieldValue + "" + categoryPart3;
for (var i = 0; i < newCategoryNode.length; i++) {
newCategoryNode[i].innerHTML=str;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
<script>
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategory = document.getElementsByClassName('categories');
var div = document.createElement('div');
div.setAttribute('class', 'categories');
var a = document.createElement('a');
a.setAttribute('class', 'titles');
var hr = document.createElement('hr');
var input_check = document.createElement('input');
input_check.setAttribute('type', 'checkbox');
input_check.setAttribute('class', 'check');
var input = document.createElement('input');
input.setAttribute('type', 'text');
var br = document.createElement('br');
var textnode = document.createTextNode(fieldValue);
div.appendChild(input);
div.appendChild(a);
div.appendChild(hr);
div.appendChild(input_check);
div.appendChild(textnode);
div.appendChild(input);
div.appendChild(br);
div.appendChild(br);
console.log(div);
var node = document.getElementsByClassName('categories');
for (var i = 0; i < node.length; i++) {
node[i].appendChild(div);
}
}
</script>
</html>
hope this could give you idea on how to do it.
you cannot use appendChild to a node using a string it shoud also be a DOM element
you can check on document.createElement and document.createTextNode function
hope it would help you more on your understanding
According to MDN, Node.appendChild() wants a Node object as its argument. It won't create one from a string of markup, so you'll have to create it yourself.
You can use document.createElement() to create a Node object, then you can set its innerHTML as you like. Once the Node is all set how you want, you can add it to the DOM using appendChild().
If you want to use appendChild() mehtod it doesn't work this way.First you have to create a child using element.createElement() method.Now concentrating on your code i encountered some problem. your getElementsByClassName is returning a nodelist containing all the elements having same class.So if you want to grab it provide it an index.As you have only one it's better to provide [0] index to it.
var newCategoryNode = document.getElementsByClassName('categories')[0];
if you don't provide index in getElementsByClassName() you can also access it
newCategoryNode[0].innerHTMM=str
i removed for loop from you code.If you want to use loop use for...in loop instead as it is a list of object.
var newCategoryNode = document.getElementsByClassName('categories');
for(key in newCategoryNode){
newCategoryNode[key].innerHTML=str;
}
you haven't defined checkAll() function related to one of your input tag.That surely get you an error.I've modified your code and it might give you the result you want
function addField() {
console.log('logged');
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories')[0];
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
console.log(categoryPart1);
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + fieldValue + "" + categoryPart3;
console.log(str);
newCategoryNode.innerHTML =str;
}
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onClick="addField();" value="Press">

How to Validate Multiple radio buttons

How can I validate multiple radio buttons. All these radio buttons generated dynamically.
<input type="radio" name="answer_option1" value="1" id="ans_options1" />
<input type="radio" name="answer_option1" value="2" id="ans_options2" />
<input type="radio" name="answer_option1" value="3" id="ans_options3" />
<input type="radio" name="answer_option1" value="4" id="ans_options4" />
<input type="radio" name="answer_option2" value="5" id="ans_options5" />
<input type="radio" name="answer_option2" value="6" id="ans_options6" />
<input type="radio" name="answer_option2" value="7" id="ans_options7" />
<input type="radio" name="answer_option2" value="8" id="ans_options8" />
<input type="radio" name="answer_option3" value="9" id="ans_options9" />
<input type="radio" name="answer_option3" value="10" id="ans_options10" />
<input type="radio" name="answer_option3" value="11" id="ans_options11" />
<input type="radio" name="answer_option3" value="12" id="ans_options12" />
<input type="radio" name="answer_option4" value="13" id="ans_options13" />
<input type="radio" name="answer_option4" value="14" id="ans_options14" />
<input type="radio" name="answer_option4" value="15" id="ans_options15" />
<input type="radio" name="answer_option4" value="16" id="ans_options16" />
Try this http://jsfiddle.net/aamir/r9qR2/
Since each group has different name attribute so you have to do validation for each set of radio buttons.
if($('input[name="answer_option1"]:checked').length === 0) {
alert('Please select one option');
}
If you have unlimited number of groups. Try this http://jsfiddle.net/aamir/r9qR2/2/
//Make groups
var names = []
$('input:radio').each(function () {
var rname = $(this).attr('name');
if ($.inArray(rname, names) === -1) names.push(rname);
});
//do validation for each group
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length === 0) {
console.log('Please check ' + name);
}
});
If you want to show just 1 error for all groups. Try this http://jsfiddle.net/aamir/r9qR2/224/
try this new fiddle http://jsfiddle.net/Hgpa9/3/
$(document).on("click","#validate", function() {
var names = [];
$('input[type="radio"]').each(function() {
// Creates an array with the names of all the different checkbox group.
names[$(this).attr('name')] = true;
});
// Goes through all the names and make sure there's at least one checked.
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if (radio_buttons.filter(':checked').length == 0) {
alert('none checked in ' + name);
}
else {
// If you need to use the result you can do so without
// another (costly) jQuery selector call:
var val = radio_buttons.val();
}
}
});
var names = []
$('input[name^="answer_option"]').each(function() {
var rname = $(this).attr('name');
if ($.inArray(rname, names) == -1) names.push(rname);
});
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length == 0) {
console.log('Please check ' + name);
}
});

Categories

Resources