How will i prevent duplication of value and empty value - javascript

How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>

To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}

Related

Range slider filter with pure javascript by adding a function to my array.prototype

I have a table populated with animals and need to filter them by population and i want to use a range slider to filter them without using jQuery, just plain javascript, already have 2 filters using array.prototype. Here is my html code:
<fieldset>
<legend>Search by population</legend>
<input id="populationSlider" class="range-slider__range" type="range" value="100" min="194" max="500000" onchange="updateSliderNumber('populationNumber', this.value);">
<input id="populationNumber" type="number" value="100" min="194" max="500000" onchange="updateSliderNumber('populationSlider', this.value);">
<span class="range-slider__value"></span>
</fieldset>
and here is my sript:
(function(document) {
var AnimalFilter = (function(Arr) {
var _input;
var _select;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _onSelectEvent(e) {
_select = e.target;
var tables = document.getElementsByClassName(_select.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filterSelect);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
function _filterSelect(row) {
var text_select = row.textContent.toLowerCase(), val_select = _select.options[_select.selectedIndex].value.toLowerCase();
row.style.display = text_select.indexOf(val_select) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('table-filter');
var selects = document.getElementsByClassName('select-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
Arr.forEach.call(selects, function(select) {
select.onchange = _onSelectEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
AnimalFilter.init();
}
});
})(document);
// Range-slider
function updateSliderNumber(id, value){
document.getElementById(id).value = value;
}
Ant suggestions?Do i need to call another function, or extend my prototype.array?
Thank you in advance!

Dynamic search form using jquery

I am trying to create a search form using jquery for following tasks to do:
A user can upload file or input text into the text area or select option from the drop-down menu but these options will appear based on the selection of 1st drop-down menu.
The user can clone this form number of times but not more than max options of the 1st drop-down menu.
The user can remove form < max options from the 1st drop-down menu.
But problems are:
Task 1 is working only on the original form but not in cloned one.I think due to the tag id, it only does the task for original one, so how can I do that for multiple occasion?
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$('#alarm_action').change(function (e) {
if ($("#alarm_action").val() == "listofcompany") {
$('#filefield').show();
$("#myTextarea").hide();
$("#showForProg").hide();
} else if ($("#alarm_action").val() == "runprogram") {
$('#filefield').hide();
$("#myTextarea").hide();
$("#showForProg").show();
} else {
$('#filefield').hide();
$("#myTextarea").show();
$("#showForProg").hide();
}
});
$(addButton).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication" name="searchtype" id="alarm_action" required>\
<option value="cityname">City Name</option>\
<option value="listofcompany">Company</option>\
<option value="runprogram">Run Program</option></select>\
<body onload="setProg();">\
<select name="searchtermorg" id="showForProg" style="display: none;"></select>\
</body>\
<input id="filefield" type="file" name="foofile" style="display: none;"/>\
<textarea id="myTextarea" name="something" ></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).find('option:selected').text()+' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type !=""){
if (query.type == "listofcompany") {
query.value =$(field).find('#filefield').val();
} else if (query.type == "runprogram") {
query.value =$(field).find('#showForProg').val();
} else {
query.value =$(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else{
slectedall=false;
}
});
var url = window.location.href;
url+="/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() ===""){
fillupfield=false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
var progarray = ['Python','Java','R'];
function setProg() {
var newOptions=progarray;
var newValues=progarray;
selectField = document.getElementById("showForProg");
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++)
{
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication" name='searchtype' id="alarm_action" required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body onload="setProg();">
<select name="searchtermorg" id="showForProg" style="display: none;"></select>
</body>
<input id="filefield" type="file" name="foofile" style="display: none;"/>
<textarea id="myTextarea" name="something"></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Can anybody help me to fix these problems? thank you
Issues with our current code:
In a valid HTML, idof an element should be unique. But here you are repeating the element id every time you clone the elements. Use class instead of id.
Use $.on to bind events to elements which are added dynamically (eg, the dropdown change event)
Spaghetti code which is not maintainable - I've tried cleaning up a bit. But there is a lot of scope for clean up.
I've fixed the issue which you have mentioned by fixing the above-mentioned points. But as I said, there is a lot of clean-up to be done before this could be used in a project.
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
var progarray = ['Python', 'Java', 'R'];
wrapper.append($("#content-template").html());
//alert($(".showForProg").length);
setProg($(".showForProg"));
$(document).on('change', '.alarm_action', function(e) {
var $container = $(this).parents('.form-field');
if ($(this).val() == "listofcompany") {
$('.filefield', $container).show();
$(".myTextarea", $container).hide();
$(".showForProg", $container).hide();
} else if ($(this).val() == "runprogram") {
$('.filefield', $container).hide();
$(".myTextarea", $container).hide();
$(".showForProg", $container).show();
} else {
$('.filefield', $container).hide();
$(".myTextarea", $container).show();
$(".showForProg", $container).hide();
}
});
$(addButton).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
wrapper.append($("#content-template").html());
setProg($(".showForProg").last());
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change', 'select.removeDuplication', function(e) {
e.preventDefault();
var cI = $(this);
var others = $('select.removeDuplication').not(cI);
$.each(others, function() {
if ($(cI).val() == $(this).val() && $(cI).val() != "") {
$(cI).val('');
alert($(this).find('option:selected').text() + ' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall = true;
var fillupfield = true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type != "") {
if (query.type == "listofcompany") {
query.value = $(field).find(',filefield').val();
} else if (query.type == "runprogram") {
query.value = $(field).find(',showForProg').val();
} else {
query.value = $(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else {
slectedall = false;
}
});
var url = window.location.href;
url += "/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() === "") {
fillupfield = false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall === false) {
alert('Please select option.');
} else {
if (fillupfield === false) {
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
function setProg($programDropdown) {
$.each(progarray , function(key, value) {
$programDropdown
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<script type="text/template" id="content-template">
<div class="repeat-container">
<div class="form-field">
<select class="alarm_action removeDuplication" name='searchtype' required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body>
<select name="searchtermorg" class="showForProg" style="display: none;"></select>
</body>
<input class="filefield" type="file" name="foofile" style="display: none;" />
<textarea class="myTextarea" name="something"></textarea>
</div>
</div>
</script>

Store default values and use in comparison in click event

The code is not complete atm but demonstrates what i'm trying to do. In my script i have a jQuery function that is storing the default values from all textareas when the pages is first loaded in an array "defaultValues". When the "click function is executed and the idea is to use the array "defaultValues" in the "CheckTextChange" function and check if anny item dosn't match "currentVal". If currentVal has another value a text change has been made and CheckTextChange will return true. I'm wondering, how can i access "defaultValues[]" inside CheckTextChange and how can i use defaultValues[] in the if-statement to check weather anny item dosn't match currentVal?
HTML:
<h3>Text1...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />
Script:
$('#btnClick').on("click", function () {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
var defaultValues = [];
$(document).ready(function(){
$('.txt').each(function () {
var defValue = $(this).get(0).defaultValue;
defaultValues.push(defValue);
var v = defaultValues[0];
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != previousVal) {
isChanged = true;
}
});
return isChanged;
}
you can save the default values as a data attrib...
$(document).ready(function() {
$(".txt").each(function() {
$(this).attr("data-deftxt", $(this).val());
});
});
$('#btnClick').on("click", function() {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function() {
var currentVal = $(this).val();
if ($(this).val() !== $(this).data("deftxt")) {
isChanged = true;
}
});
return isChanged;
}
Use an associative mapping:
var defaultValues = {};
$(document).ready(function(){
$('.txt').each(function () {
defaultValues[$(this).attr('id')] = $(this).val();
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultValues[$(this).attr('id')]) {
isChanged = true;
}
});
return isChanged;
}
And set an ID to your fields:
<h3>Text1...</h3>
<textarea class="txt" id="field1">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt" id="field2">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt" id="field3">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />
You have to break the loop as follow
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function (index) {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultVaules[index]) {
isChanged = true;
return;
}
});
return isChanged;
}

jQuery multiple validation

I have here a form validation. I used this validation in multiple editing records in php. I have two textbox that comparing it's value. I tried to mix my validation script and comparing value script but isn't working properly.
This what I have now but I'm having problem with this when I tried to input lower value in n_quanity field the validation error message is not working and it allowed the form to submit. I want to display error in span not alert the message. Help please?
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
for (var i = 0,len=textBox1.length; i < len;i++) {
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
return false;
} else {
$(this).next("span.val_qty").html("");
}
}
});
And this is my full code
<script>
jQuery(function($) {
var validation_holder;
$("form#register_form input[name='submit']").click(function() {
var validation_holder = 0;
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else {
$(this).next("span.val_qty").html("");
}
});
if(validation_holder == 1) { // if have a field is blank, return false
$("p.validate_msg").slideDown("fast");
return false;
} validation_holder = 0; // else return true
/* validation end */
}); // click end
}); // jQuery End
</script>
<script>
$('#sbtBtn').on('click', function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0,len=textBox1.length; i < len;i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
alert('value is greater than quantity');
return false;
} else {}
}
});
</script>
<p> <label for="">PR Quantity</label> <input name="n_quantity[]" id="n_quantity" class="qty n_quantity" type="text"/><span class="val_qty"></span> </p>
<p style="display:none;"><input id="pr_total" class="pr_total" type="text"></p>

I want to Empty the Value of 2 Input-Type-Text, On Checked (Box)

Guys I Need Help I have the Code what can Empty the Value of Single Input by ID i have 2 Input lets say Start time and End time When i Click on All Day it should be Empty Start Time and End Time When i Check this Button...
Here is my Code....
<Input type="text" id="startime" />
<input type="text" id="endtime" />
<input type="check" id="remove" />
<script type="text/javascript">
var imgInput = document.getElementById('startime'),
remove = document.getElementById('remove'),
val = imgInput.value;
remove.onchange = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
</script>
Help Appreciated...
For a checkbox, you should not use the onchange event handler, onclick will do what you need:
remove.onclick = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
However it looks like you might be trying to save the value if it gets cleared so it can be repopulated, if this is the case then you also need to update val before you clear the text box:
remove.onclick = function() {
if (this.checked) {
val = imgInput.value;
imgInput.value = "";
} else {
imgInput.value = val;
}
}

Categories