Disallowing to select already selected value in combobox using JQUERY - javascript

Hi I have the following code for appending comboboxes when button is clicked.
I want to check if the value is selected in any previous combobox if it is selected then alert "value is already selected".
For example, I have 5 comboboxes appended and the value in each combobox should be different from each other by traversing each value in the comboboxes:
<div class="custom-control custom-checkbox">
<input type="checkbox" class="itemRow custom-control-input" id="itemRow_1">
<label class="custom-control-label" for="itemRow_1"></label>
</div>
<div class="form-group has-success">
<select name="proid[]" class="form-control" id="proid_1" required="required">
</select>
</div>
<div class="form-group has-success">
<button type="button" name="addbtn" id="addbtn" class="btn btn-success">Add Product</button>
</div>
JQUERY CODE
var count = $(".itemRow").length;
$(document).on('click', '#addbtn', function() {
count++;
var productcombo='';
productcombo += '<tr>';
productcombo +='<td><input type="checkbox" class="custom-control-input itemRow" id="itemRow_'+count+'"> <label class="custom-control-label" for="itemRow_'+count+'"></label> </td>';
productcombo +='<td><select name="proid[]" class="form-control" id="proid_'+count+'" required="required"> </select></td>';
productcombo += '</tr>';
$('#products').append(productcombo);
});
$("#proid_"+count).change(function()
{
var id = $(this).find(":selected").val();
// code here to compare each value
if(value found in previous comboboxes)
{
alert("Already Selected");
}
});

You can set an array variable and when user select a value of combobox, push the value in it.
var selectedVals = [];
$("#proid_"+count).change(function() {
var id = $(this).find(":selected").val();
// code here to compare each value
if(selectedVals.includes(id)) {
alert("Already Selected");
} else {
selectedVals.push(id);
}
});

Related

I want to catch all labels of checked checkbox in javascript

Is there a way to catch all the label texts of a checked checkbox in Javascript (not JQuery).
My HTML is:
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
I want to catch the label of the checked checkbox in Javascript in order to use it as Javascript Variable in Google Tagmanager.
Currently I've got this code (from www.simoahava.com) to catch the values of the checked checkboxes.
function () {
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-containter input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(inputs[i].value);
}
}
return selectedCheckboxes;
}
This script gives me all the values, but these are none-descriptive values. But I want the descriptive labels.
Is there a way to catch the text within the span with class .wpgu-onboarding-answer-title of all checked checkboxes ?
Thanks in Advance
Erik.
Apart from the previous solution, would like to share one more simple solution based on the code mentioned in the question. The solution can be as simple as fetching all the labels with class as wpgu-onboarding-answer-title and based on which input element is selected, fetch the respective label index and use it.
Please note that I have added an extra button for testing the function easily.
function abc() {
var labels = document.querySelectorAll('.wpgu-onboarding-answer-title');
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-container input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(labels[i].textContent);
//selectedCheckboxes.push(inputs[i].value);
}
}
console.log(selectedCheckboxes);
return selectedCheckboxes;
}
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
<button onclick="abc()">
Fetch All Chkbox Values
</button>
Please note that this solution would only work if you have wpgu-onboarding-answer-title class being used for only this purpose and not anywhere else in the page before.
Based on this answer using jQuery, you can use an attribute selector and the ID of the element you want to get the label for, e.g. document.querySelector('label[for=' + button.id + ']'), then get its textContent to get the actual label:
document.querySelectorAll('input.wpgu-onboarding-answer-checkbox').forEach(input => {
console.log(input.id + ' ' +
document.querySelector('label[for=' + input.id + ']').textContent.trim() + ' ' +
(input.checked? '' : 'not ') + 'checked'
)
});
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
This could help you.
var inputs = document.querySelectorAll(".wpgu-onboarding-answer-container input:checked+label>span");
var checkbox = [];
inputs.forEach(input=>{
checkbox.push(input.textContent);
console.log(input.textContent)
});
Good lucky!

Increment class/ID to carry function to cloned element

I have a section of code that contains a dropdown and 3 readonly input fields. The input fields are populated using javascript, this works fine on it's own using the below code -
$(document).on('change', '.unit', function(e) {
//Getting Value
var role = $('.unit option:selected').data('role');
var power = $('.unit option:selected').data('power');
var type = $('.unit option:selected').data('type');
//Setting Value
$(".role").val(role);
$(".power").val(power);
$(".type").val(type);
});
I am wanting to clone the element using this code -
//define template
var template = $('.duplicate-sections .form-section:first').clone();
//define counter
var sectionsCount = 1;
//add new section
$('body').on('click', '.addsection', function() {
//increment
sectionsCount++;
//loop through each input
var section = template.clone(true, true).find(':input').each(function(){
//set id to store the updated section number
var newId = this.id + sectionsCount;
//update for label
$(this).prev().attr('for', newId);
//update id
this.id = newId;
}).end()
//inject new section
.appendTo('.duplicate-sections');
return false;
});
//remove section
$('.duplicate-sections').on('click', '.remove', function() {
//fade out section
$(this).closest('.form-section').fadeOut(300, function(){
$(this).closest('.form-section').empty();
});
return false;
});
The cloning process works and the dropdown and the inputs are cloned. However when populating the cloned input fields it uses the values from the parent not the clone.
My html is -
<div class="duplicate-sections">
<div class="form-section">
<div class="form-group row">
<label for="inputFirstName" class="col-form-label col-sm-3 text-left text-sm-right">Unit Type</label>
<div class="col-sm-3">
<select name="unit" id="unit" class="form-control unit"><option value="">Select</option><option
data-role="HQ" data-power="4" data-type="Company Commander" value="1">Ehrwig Arellano</option>
<option data-role="HQ" data-power="6" data-type="Company Commander" value="2">Ehrwig
Arellano</option>
<option data-role="HQ" data-power="2" data-type="Tempestor Prime" value="3">Tempestor Prime</option>
</select></div>
<div class="col-sm-2 increment_controls">
<input type="text" id="role" name="role" class="form-control role" readonly placeholder="Role">
</div>
<div class="col-sm-1 increment_controls">
<input type="text" id="power" name="power" class="form-control power" readonly placeholder="PL">
</div>
<div class="col-sm-3 increment_controls">
<input type="text" id="type" name="type" class="form-control type" readonly placeholder="Type">
</div>
</div>
<label for="inputFirstName" class="col-form-label col-sm-3 text-left text-sm-right">
</label><input class="remove col-sm-9" type="button" value="Remove Unit"></input>
</div>
</div>
<label for="inputFirstName" class="col-form-label col-sm-3 text-left text-sm-right"></label>
<input class="addsection col-sm-9" type="button" value="Add Unit"></input>
The whole thing can be found here - JSFiddle
You need to update change event handler script for Unit as here you need to update input fields from the relevant form section only and not for all input fields.
see below code
$(document).on('change', '.unit', function(e) {
//Getting Value
var $option = $(this).find('option:selected');
var role = $option.data('role');
var power = $option.data('power');
var type = $option.data('type');
//Setting Value
var $parent = $(this).closest('.form-section');
$parent.find(".role").val(role);
$parent.find(".power").val(power);
$parent.find(".type").val(type);
});
Demo JSFiddle

Display the form array inputs value before submitting the form

i have a single page which is divided into two sections.So at first first section is seen and we need to fill the inputs value and when we click go to next page button then the first section is now hidden and second section is shown.Then only we can submit the form.
Now what i want is that in the first section, i have four inputs like shown below
<div class="room_details_first col-md-12" id="first_order">
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]"/>
</div>
</div>
Now by using jquery i have append the inputs and the code is shown below
function add_others_order(){
var output="";
output+= '<div class="room_details_first col-md-12" id="first_order">';
output+='<div class="col-md-3"><input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/></div>';
output+='<div class="col-md-3"> <input type="text" placeholder="Hotel Name" name="others_hotel[]"/> </div>';
output+='<div class="col-md-3"><input type="text" placeholder="Hotel price" name="others_hotel_price[]"/></div>';
output+='<div class="col-md-2"> <input type="text" placeholder="Customer Price" name="others_client_price[]"/></div>';
output+='<div class="col-md-1" ><i class="fa fa-remove"></i></div>';
output+='</div>';
$('#first_order').after(output);
}
now what i need is i need to save the inputs value before submitting and list it in second section of the page.i have tried to do it but i am failed many times. And i have also found similar answers which is given below
Display the data entered in a form before submitting the form
Guys i need help.
Here is what you want, you will get all input's value and you can do
what ever you want with it.
function nextStep() {
var allFields = document.getElementsByTagName("input");
//console.log(allFields);
for (var index in allFields) {
console.log('name : '+allFields[index].name);
if (allFields[index].type == "text") { // you can change condition by name instead of type
if (allFields.hasOwnProperty(index)) {
var attr = allFields[index];
console.log(attr.value)
}
}
}
}
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]" />
</div>
<input type="button" onclick="nextStep()" value="Next step">
I think this is what you want, or as close to what you need, I add an Id attribute so you can do add/remove:
var stored_data = [];
stored_data.total = 0;
$('#dummy').on('click', function(){
var obj = {
id: stored_data.length,
food: food.value,
hotel_name: hotel_name.value,
hotel_price: hotel_price.value,
customer_price: customer_price.value
};
stored_data.push(obj);
stored_data.total += parseInt(obj.customer_price);
//$('#first_section').hide();
var output = '<div class="room_details_first col-md-12" id="first_order">';
output += '<div>Order ' + obj.id + '</div>';
output += '<div class="col-md-3">Food: ' + obj.food + '</div>';
output += '<div class="col-md-3">Hotel Name: ' + obj.hotel_name + '</div>';
output += '<div class="col-md-3">Hotel Price' + obj.hotel_price + '</div>';
output += '<div class="col-md-2">Customer Price' + obj.customer_price + '</div>';
output += '<div class="col-md-1" ><i class="fa fa-remove"></i></div>&nbsp';
$('#new_section').append(output);
$('#total').text(stored_data.total);
});
https://jsfiddle.net/5uka65tx/2/
Here's a way to do it by using clone() on the whole first order and do some modifications to add the link and change duplicate ID and last item column class.
First use serializeArray() to get the values to store
var values = $('#first_order :input').serializeArray();
console.log(values);
then clone , modify and insert
var link = '<div class="col-md-1" ><i class="fa fa-remove"></i>LINK</div>';
// clone first order and update ID
var $first = $('#first_order').clone().attr('id', 'first-order_2');
// modify column on last one and add the link
$first.children(':last').toggleClass('col-md-2 col-md-3').after(link);
// insert in second position
$('#second').append($first)
DEMO
By taking reference of Jigar7521, i tried to do the following way
var allFields = document.getElementsByClassName("others_order");
var others_total_price='0';
var others_food_items=new Array();
var others_hotel_name=new Array();
var others_hotel_price=new Array();
var others_client_price=new Array();
//var others['food_items'] = new Array();
var ficounter=0;
var hcounter=0;
var hpcounter=0;
var cpcounter=0;
Array.prototype.forEach.call(allFields, function(el) {
if(el.name=='others_client_price[]'){
others_client_price[cpcounter]=el.value;
cpcounter++;
others_total_price=parseFloat(others_total_price)+parseFloat(el.value);
}
if(el.name=='others_food_items[]'){
others_food_items[ficounter]=el.value;
ficounter++;
}
if(el.name=='others_hotel[]'){
others_hotel_name[hcounter]=el.value;
hcounter++;
}
if(el.name=='others_hotel_price[]'){
others_hotel_price[hpcounter]=el.value;
hcounter++;
}
});
$('#others_total_price').val(others_total_price);
var others_output="<h4>Others Order</h4>";
for(var i=0;i<=ficounter;i++){
others_output+='<div ><div class="col-md-12"><div class="col-md-3">'+others_food_items[i]+'</div><div class="col-md-3">'+others_hotel_name[i]+'</div><div class="col-md-3">'+others_hotel_price[i]+'</div><div class="col-md-3"> '+others_client_price[i]+'</div></div></div>';
}
$('#others_id').html(others_output);
it worked but i get errors like undefined
i tried to console.log every array and i got what i did not have expected

jQuery on change don't return attribute value

Have problem to display select on change attribute id.
PHP:
<form action="" class="form-inline">
<div class="form-group">
<select name="kategorijos" id="kategorijos" class="category form-control" onchange="fetch_select_category(this.value);">
<option value=""></option>
FOREACH
</select>
</div>
<div class="form-group">
<fieldset disabled>
<select id="disabledSelect" name="subcategories" class="subcategory form-control" onchange="fetch_select_product(this.value);" required>
<option value="" disabled selected>Select Subcategory</option>
</select>
</fieldset>
</div>
<div class="form-group">
<td><input type="text" name="gramai" class="form-control" value=""></td>
</div>
<div class="form-group" id="kalb">
<input type='text' name='1[]' value="-" disabled>
<input type='text' name='12[]' value="-" disabled>
<input type='text' name='123[]' value="-" disabled>
<input type='text' name='1234[]' value="-" disabled>
</div>
</form>
My jquery code:
$("select").on('change', function() {
var status = $('select').attr('id');
alert(status);
});
var categoryId = 0;
var category = 0;
var product = 0;
var disableId = 0;
$("#add").click(function () {
categoryId = categoryId + 1;
category = category + 1;
product = product + 1;
disableId = disableId + 1;
$("#item").append('<div class="col-xs-12"><form action=""
class="form-inline"><div class="form-group"><select name="kategorijos"
**....... same code as above (php)**
});
When I select the first row it alerts value. But then I add new row with add button, and then change second select the alert don't work, and I don't get the select id. Where can be the problem? Maybe it doesn't work with append html ?
You need to use event delegation for dynamically generated element and also use this instead of 'select' to get the id of dropdown.
$(document).on('change', 'select', function() {
var status = $(this).attr('id');
alert(status);
});

How to serialize checkbox value through searilizedarray()?

My question is how to serialize checkbox value and textbox value together in one array through searilizedarray()...
now i am getting something like this
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"Option one"},
{"name":"wpc_chkbox[]","value":"Option two"},
{"name":"wpc_chkboxasdf[]","value":"Option one"},
{"name":"wpc_chkboxasdf[]","value":"Option two"},
{"name":"wpc_inline_chkbox[]","value":"1"},
{"name":"wpc_inline_chkbox[]","value":"2"},
{"name":"wpc_inline_chkbox[]","value":"3"},
{"name":"wpc_radios","value":"Option one"}]
but it should be like
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"[Option one,Option Two]"},
{"name":"wpc_chkboxasdf[]","value":"[Option one,Option Two]"},
{"name":"wpc_inline_chkbox[]","value":"[1,2,3]"},
{"name":"wpc_radios","value":"Option one"}]
i am using var form = $('.wpc_contact').serializeArray(); to get form data
this is my html sample which I am generating dynamically using drag and drop future..
<form method="POST" name="1" class="form-horizontal wpc_contact" novalidate="novalidate">
<fieldset>
<div id="legend" class="">
<legend class="">Demo</legend>
<div id="alert-message" class="alert hidden" style="color: red;"></div>
</div>
<div class="control-group">
<label class="control-label">Checkboxes</label>
<div class="controls" name="wpc_chkbox" req="yes">
<input type="checkbox" value="Option one" id="wpc_chkbox_0" name="wpc_chkbox[]" req="yes"> Option one
<input type="checkbox" value="Option two" id="wpc_chkbox_1" name="wpc_chkbox[]" req="yes"> Option two
</div>
</div>
<div class="control-group">
<div class="controls" name="wpc_inline_chkbox" req="yes">
<input type="checkbox" value="1" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_0" req="yes"> 1
<input type="checkbox" value="2" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_1" req="yes"> 2
<input type="checkbox" value="3" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_2" req="yes"> 3
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
Thanks in advance
Try this:
var cacheObject = {};//tmp cache for form elements name/values pairs
var serArr = $('.wpc_contact').serializeArray();
//set values of elements to cacheObject
$.each(serArr, function (arrayIndex,obj) {
if (cacheObject[obj.name]) {
cacheObject[obj.name].push(obj.value);
} else {
cacheObject[obj.name] = [obj.value];
}
});
//create new serialized array
var newSerArr = [];
$.each(cacheObject, function (key, value) {
var obj = {};
obj[key] = value;
newSerArr.push(obj);
});
console.log(newSerArr);//looks like serializeArray
This one makes a different array and elements of same name are grouped together.
var form_data = $(".wpc_contact").serializeArray();
var form_array = {}; //final array where all the values will be stored
$.each(form_data, function(i, element) {
if(jQuery('input[name="'+element.name+'"]:checked').length>0)
{
replaced = element.name.replace('[]',''); //removing [] from the input name
form_array[replaced]={};
jQuery('input[name="'+element.name+'"]:checked').each(function(j,ind){
form_array[replaced][j] = jQuery(this).val();
});
}
else
{
form_array[element.name] = element.value;
}
});
console.log(form_array);
You can access as:
alert(form_array['wpc_chkbox'][0]); //no '[]' in the key

Categories