i have a problem in preventing duplicates from being entered, i’m generated radio buttons dynamically in 2 pages at the same time using exactly one button, i take the label from the user and generate a radio button from that label, i want to prevent the user from entering 2 identical labels, here’s the script which generates radios for the 2 pages any help will be appreciated
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<input />', {
'type': 'radio',
'fieldset':'group',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'b',
'value': '1'}));
$('#after').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}
function createRadioFortSecondPage(elem, label, checked) {
var id = 'option1_' + label;
$('#Inserthere').append($('<input />', {
'type': 'radio',
'fieldset':'group',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'b',
'value': '1'}));
$('#Inserthere').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}
that’s the function i wrote to prevent duplicates:
function checkDublicates(){
var isExist=true;
var x = document.getElementById('option').value;
var labels = [];
$('#after input[type=radio]').each(function() {
labels.push($('label[for='+$(this).attr('id')+']').text());
});
for(var i=0;i<labels.length;i++){
if(x==labels[i])
{
isExist=false;}
else{
isExist=true;}
}
return isExist;}
and that’s the button action:
$('#AddButton').click(function(){
var exist=checkDublicates();
<!--var isEmpty=validate();-->
<!--if(exist==true){
<!--alert("Duplicates Are Not Allowed!");
<!--}else{
var y=document.getElementById('question').value
document.getElementById('headTitle').innerHTML=y;
if(exist==false){
alert("Duplicates Not Allowed!")
}else{
createRadioElement(this,$('#option').val(),true);
createRadioFortSecondPage(this,$('#option').val(),true);
}
});
Just use
$.inArray(val, arr)it will work ! http://api.jquery.com/jQuery.inArray/But just a comment concerning your code.
Replace
by
and
by
Will be much cleaner 😉