Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show alert for duplicated value of textbox

I have multiple input fields with different values. I can edit them but cannot be empty (if empty show an alert). When I am editing it to new values, if the new value matches with any of the other inputs values, I need an alert that you cannot use this.

HTML

<input type="text" class="selector" value="new">
<input type="text" class="selector" value="old">
<input type="text" class="selector" value="newest">
<input type="text" class="selector" value="oldest">
<input type="text" class="selector" value="older">

JavaScript

$('.selector').change(function () {
    alert();
});

Fiddle here

like image 363
Raviteja Avatar asked Dec 03 '15 09:12

Raviteja


People also ask

How do I get TextBox value to show in alert?

Displaying (Showing) TextBox value in Alert using jQuery Inside the jQuery document ready event handler, the Button has been assigned a jQuery Click event handler. When the Button is clicked, the TextBox value is retrieved and displayed in JavaScript Alert Box.

How can check duplicate value in TextBox using jQuery?

var $inputsWithSameValue = $('input[value=' + $(this). val() + ']'); hasDuplicates = $inputsWithSameValue.


2 Answers

Updated Fiddle.

You can refresh the value attribute using $(this).attr('value', $(this).val()); first, then check if there's any other field with class selector has the same value using value selector $('.selector[value="' + current_value + '"]').length.

Hope this helps.


$('body').on('blur', '.selector', function () {
    $(this).attr('value', $(this).val());

    if ($('.selector[value="' + $(this).val() + '"]').length > 1 ) {
        $(this).focus();
        alert('You cannot use this');
    }else if($(this).val().length == 0) {
        alert('Empty value not accepted');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="selector" value="new">
<input type="text" class="selector" value="old">
<input type="text" class="selector" value="newest">
<input type="text" class="selector" value="oldest">
<input type="text" class="selector" value="older">
like image 194
Zakaria Acharki Avatar answered Nov 15 '22 08:11

Zakaria Acharki


Try this Code:

$('.selector').on('blur',function () {
   if ($('.selector[value="'+$(this).val()+'"]').not($(this)).length > 0 || current_value.length == 0 ) {
    alert('duplicate value');
   }
});

http://jsfiddle.net/0c0qep6y/12/

like image 44
madalinivascu Avatar answered Nov 15 '22 08:11

madalinivascu