User have some list (exactly list, but not the point). User can add to list some other unique elements - strings. Form, allowing to submit new element, is hidden. To add new one user press button "Show Add Fruit Form", form appears, getting string, and if string unique, push it to string, if not - alert message.
Problem is:
- At first adding all works fine.
- At second and next adding if:
-
- string unique - string push to array and alert message about string not unique
-
- string not unique - multiple one by one alerts message about string not unique
html:
<div id="plus_tab">Show Add Fruit Form</div>
<div id="div_form" class="hidden">
<form id="my_form" >
<input type="text" name="value1"/>
<input type="submit" value="Add fruit"/>
</form>
</div>
<div id="result">
result
</div>
js:
var fruits = ['apple', 'strawberries']
$('#plus_tab').click(function(){
$("#div_form").removeClass('hidden').addClass('visible')
$("#my_form").submit(function(event){
event.preventDefault()
new_fruit = $(this).find('input[name="value1"]').val()
if ($.inArray(new_fruit, fruits)==-1 ){
fruits.push(new_fruit);
$('#result').empty().append(fruits);
$("#div_form").removeClass('visible').addClass('hidden');
}else {
alert('Name '+new_fruit+' exist, choose other')
}
})
})
css:
.hidden {
display: none;
}
.visible {
display: block;
}