简体   繁体   中英

how to prevent duplicated entries in javascript?

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

document.getElementById('question').value

by

$('#question').val()

and

document.getElementById('headTitle').innerHTML=y

by

$('#headTitle').html(y)

Will be much cleaner ;-)

You can use this handy function to push elements into an array and check for duplicates at the same time. It'll return true if it catches a duplicate.

var noDupPush = function (value, arr) {

    var isDup = false;

    if (!~$.inArray(value, arr)) {
        arr.push(value);
    } else {
        isDup = true;
    }

    return isDup;

};

// You can use it like this

var arr = ['green'];
if (noDupPush('green', arr)){
  // Dup exists
}
// Or else it will just push new value to array

You could generate an id that includes the text of the label and then very quickly check for the existence of an element containing that text. For example:

function generateLabelId( userinput ){ 
    return 'awesomelabel_' + userinput.replace(/\W/g,'');
}

var label = document.getElementById(generateLabelId( userinput ));
var labelDoesNotExist = (label == undefined );

if (labelDoesNotExist){
    // create your element here
    // making sure that you add the id from generateLabelId
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM