I am trying to construct the url parameters for the from the value selected from the input elements.
for example: i have a page where there is a one text input field and 3 select fields(name,department,brand,model),first i will enter the value to name text field,then i will select the value from department dropdown,then i wont select anything from brand dropdown, then i will select some value from model dropdown, finally when i press submit, the values which have been input by user should be put in to object with its key pair and generate the url params with $.params(obj) and append that to ajax call. how can i do it. i have the code below of what i have done.
ex:
var obj = {}
//after click on submit
obj = {
_pick:pick,
_dept:dept,
_model:model // this obj contains no brand object, because i have not selected anything from the brand dropdown
}
html:
<form name="populateForm">
<div class="dom_element">
<label>Department</label>
<input type="text" name="pick" id="pick">
</div>
<div class="dom_element">
<label>Department</label>
<select id="departmentSelect">
<option value="0">Select Department</option>
<option value="122">Department-1</option>
<option value="123">Department-2</option>
<option value="124">Department-3</option>
<option value="125">Department-4</option>
<option value="126">Department-5</option>
</select>
</div>
<div class="dom_element">
<label>Brands</label>
<select id="brandSelect">
<option value="0">Select Brand</option>
<option value="212">Brand-1</option>
<option value="213">Brand-2</option>
<option value="214">Brand-3</option>
<option value="215">Brand-4</option>
<option value="216">Brand-5</option>
</select>
</div>
<div class="dom_element">
<label>Model</label>
<select id="modelSelect">
<option value="0">Select Model</option>
<option value="328">Model-1</option>
<option value="324">Model-2</option>
<option value="326">Model-3</option>
<option value="325">Model-4</option>
<option value="322">Model-5</option>
</select>
</div>
</form>
<button class="ApplyFilter">Apply</button>
js:
$(document).ready(function(){
$('.ApplyFilter').on('click',function(){
var paramObj = {};
var pick = $('#pick').val();
var dept = $('#departmentSelect').val();
var brand = $('#brandSelect').val();
var model = $('#modelSelect').val();
if(pick != ''){
paramObj = {
_pick:pick
}
}
if(dept > 0){
paramObj = {
_dept:dept
}
}
if(brand > 0){
paramObj = {
_brand:brand
}
}
if(model > 0){
paramObj = {
_model:model
}
}
/*
this is the object i am expecting at the end, if any input does not have any value then that should not be in this object
paramObj = {
_pick:pick,
_dept:dept,
_brand:brand,
_model:model
}
*/
var urlParams = $.params(paramObj);
if(urlParams.length > 0){
$.ajax({
type: "POST",
url: "/api/getMydata/?"+urlParams,
success:function(response){
console.log(response.responseData);
}
})
}
});
});
Instead of
paramObj = {
_pick:pick
}
just do
paramObj._pick = pick;
The current way you're doing it, the paramObj object is just being reset each if statement.
Related
I have 2 picklists with the same values. In the 1st picklist, it has more values than the 2nd picklist. So when the user selects some value from the 2nd picklist, it is showing the same value in the 1st one.
But I would like to show if the value Testing 1 is selected in picklist 1 then the same value should show in the 2nd picklist. If the user selects Testing 2 from the 1st picklist then the 2nd picklist should also show the same value.
Not sure how to achieve this. Could someone help me with this?
var sMap = {};
sMap["ABC"] = ["Test2ABC", "Style"];
sMap["CDE"] = ["Test2CDE", "style"];
sMap["EFG"] = ["Test2EFG", "style"];
function onChangeRadio(ele) {
var id = $(ele).attr("id");
var type = $(ele).attr("type");
var tagName = $(ele).prop("tagName");
if (tagName.toLowerCase() == "select") {
var val = $(ele).val();
$('#codes').append($("<option value='" + val + "'>" + val + "</option>"));
setsc(val);
} else {
var Code = Object.keys(sMap).find(key => sMap[key].includes(id));
setsc(Code);
}
}
function setsc(val) {
$('[name="Code"]').val(val);
window.dispatchEvent(new Event('resize'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td id="TD1">
<input type="hidden" name="Test1" id="hidden-test1" value="">
<input list="codes" name="Code" id="slist" class="Mandatory">
<datalist id="codes">
<option value="">-- Choose one --</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
<option value="ABC">worker</option>
<option value="NAP">Port</option>
</datalist>
</td>
<select name="T-Test2" id="Test2" onchange="onChangeRadio(this)">
<option value="" selected="">Choose one</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
</select>
You need to detect the onchange event on the datalist. You do that by checking the input event on the <input>.
You can use the inputType on the InputEvent to filter out any unwanted onInput events. This is "insertReplacementText" on Firefox 81 and null for Chrome/Edge 86. If you need to support IE11 you will need to validate the value is valid.
$("#slist").on("input", (event) => {
// Detect change on the datalist
if (event.inputType == "insertReplacementText" || event.inputType == null) {
console.log(event.target.value);
})
Other explains areinside the below code.
var sMap = {};
sMap["ABC"] = ["Test2ABC", "Style"];
sMap["CDE"] = ["Test2CDE", "style"];
sMap["EFG"] = ["Test2EFG", "style"];
function onChangeRadio(ele) {
var id = $(ele).attr("id");
var type = $(ele).attr("type");
var tagName = $(ele).prop("tagName");
if (tagName.toLowerCase() == "select") {
var val = $(ele).val();
$('#codes').append($("<option value='" + val + "'>" + val + "</option>"));
setsc(val);
} else {
var Code = Object.keys(sMap).find(key => sMap[key].includes(id));
setsc(Code);
}
}
function setsc(val) {
$('[name="Code"]').val(val);
window.dispatchEvent(new Event('resize'));
}
$("#slist").on("input", (event) => {
// Detect change on the datalist
if (event.inputType == "insertReplacementText" || event.inputType == null) {
let selectedValue = event.target.value;
if (!selectedValue) return;
// Get the text of the option associate with the value
let optionData = $(`#codes > option[value="${selectedValue}"]`).text();
console.log(optionData);
// Append in the <select>
// if the otpion is not existed, use a temporary attribute, so we can clear it out later
let selectedOption = $(`#Test2 > option[value="${selectedValue}"]`)[0];
if (selectedOption) {
// selected option exists, show it
selectedOption.selected = 'selected';
} else {
// selected option doesn't exist, add then show
// Clear the temporary options out of the select
$('#Test2 > [temporary="true"]').remove();
$('#Test2').append($('<option>', {
value: selectedValue,
text: optionData,
selected: true,
temporary: true,
}));
}
}
});
// Whenever you change the value on the select, clear out the temporary options
$('#Test2').on('change', (e) => {
$('#Test2 > [temporary="true"]').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td id="TD1">
<input type="hidden" name="Test1" id="hidden-test1" value="">
<input list="codes" name="Code" id="slist" class="Mandatory">
<datalist id="codes">
<option value="">-- Choose one --</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
<option value="HIJ">worker</option>
<option value="NAP">Port</option>
</datalist>
</td>
<select name="T-Test2" id="Test2" onchange="onChangeRadio(this)">
<option value="" selected="">Choose one</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
</select>
I have a select with options and values:
<select id="sid">
<option value="sValue1">sText1</option>
...
</select>
I need to create an associated array for all pairs:
var data = {"sText1":"sValue1",...};
Is there ready/simplifies tools to do that?
It's a basic for ... on ... iteration.
Take note that if there are multiple <option> with the same label, the last one will take place in the result object.
const select = document.getElementById('sid');
const objContainer = document.getElementById('sid-obj');
const options = select.getElementsByTagName('option');
const selectObj = {};
for (const opt of options) {
let optObj = {};
optObj[opt.textContent] = opt.value;
Object.assign(selectObj, optObj);
}
// print result in code
objContainer.textContent = JSON.stringify(selectObj);
<select id="sid">
<option value="">Default</option>
<option value="sValue1">sText1</option>
<option value="sValue2">sText2</option>
<option value="sValue3">sText3</option>
<option value="sValue4">sText4</option>
<option value="sValue5">sText4</option>
</select>
<h2>Result:</h2>
<code id="sid-obj" />
Add a function to the select which will be called on change and on change get the value and the text from the selected option
function getValue(elem) {
let obj = {};
obj[elem.options[elem.selectedIndex].text] = elem.value
console.log(obj)
}
<select id="sid" onchange='getValue(this)'>
<option value="sValue1">sText1</option>
<option value="sValue2">sText2</option>
<option value="sValue3">sText3</option>
</select>
Sorry for being late to the party but here is a jQuery solution for the same.
var arr = {};
$("#sid option").each(function() {
let text = $(this).text();
arr[text] = $(this).val();
});
// print result
$('#sid-obj').append(JSON.stringify(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sid">
<option value="">Default</option>
<option value="sValue1">sText1</option>
<option value="sValue2">sText2</option>
<option value="sValue3">sText3</option>
<option value="sValue4">sText4</option>
<option value="sValue5">sText4</option>
</select>
<h2>Result:</h2>
<code id="sid-obj" />
i want to automatically select value of dropdown matching value of php variable
here is my
<select class="destinationId" id="destination" name="destinationId" onchange="getNationalityAndLiving(this.value,'','');">
<option value="" disabled selected>Select Traveling to</option>
<option data-prefix="azerbaijan" value="azerbaijan" >
Azerbaijan </option>
<option data-prefix="cambodia" value="cambodia" >
Cambodia </option>
<option data-prefix="egypt" value="egypt" >
Egypt </option>
<option data-prefix="india" value="india" >
India </option>
<option data-prefix="kenya" value="kenya" >
Kenya </option>
</select>
<select class="nationality" name="nationality" id="nationality">
<option value="" disabled selected>Select Citizen of</option>
</select>
this is my ajax code to retrive dynamic dropdown for select select option "nationality"
<script>
$(document).ready(function(){
$("#destination").change(function(){
var deptid = $(this).val();
var dbnm = "country";
var res = dbnm.concat(deptid);
$('.overlay').show();
$.ajax({
url: 'getcountry.php',
type: 'post',
data: {dest:res},
dataType: 'json',
success:function(response){
var len = response.length;
$("#nationality").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"'>"+name+"</option>");
}
$('.overlay').hide();
}
});
});
});
</script>
i have some dynamic php variable coming on this page from previous url.
for example
$nationality = "some value";
What i want is selected dropdown with value of $nationality in second dropdown,
if it was static i could have achieved this, but how to auto select in dynamic i am not able to get any workaround.
you can pass the php variable to js variable
var Nationality = "<?php echo $nationality; ?>";
then when append the option you can use
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"' "+ (Nationality.trim() == name.trim()) ? 'selected' : '' +">"+name+"</option>");
I'm trying to get the value of the option which have the attribute "selected" to compare it to the current option selected.
function onChangeOption(opt) {
var update_value = opt.value;
var selectedValue = '???'; // get selected attribute
if (update_value != selectedValue) {
// Do some things
}
}
<select class="form-control" onchange="onChangeOption(this)">
<!-- I wanna got the content of option selected=selected-->
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
// save initial selected value to a variable
var initSelected = $('.form-control option:selected').val();
$('select').on('change', function() {
// check if the selected value is the same as the initial one was
if(this.value == initSelected) {
console.log('same values');
} else {
console.log('not same values');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Just add change event listener.And get the selected value.You can achieve comparision between selected value and changed value by maintaining an array.Like below.
values = []//creates an array
select = document.querySelector('#myselect');
values.unshift(select.value);
//console.log(values);
select.addEventListener('change',function(){
update_value = this.value;
console.log(this.value);
if (update_value != values[0]) {
// alert('Not matched');
console.log('Not matched');
}
else{
//alert('Matched');
console.log('Matched')
}
});
<select class="form-control" id="myselect">
<option selected="selected" value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
I think alexis actually wants something more like this:
function onChangeOption(opt) {
var update_value = opt.value;
var options = document.getElementsByTagName("option");
if (options[0].getAttribute("selected")=="selected") {
var selectedValue = options[0].value;
} else {
var selectedValue = options[1].value;
}
if (update_value != selectedValue) {
// If the selected option's value is not equal to the value of the option with the attribute "selected", then do... (this way, you can change the attribute to any of the options!)
console.log(selectedValue);
}
}
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Comment the result and if you need anything else. Glad to help.
You can always store previously selected values, if you want to access them somehow later on: working example.
HTML:
<select id="mySelect" class="form-control" onchange="onChangeOption(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>Previous: <span id="prev"></span></p>
<p>Current: <span id="curr"></span></p>
JS:
var selectElem = document.getElementById("mySelect");
var prev = document.getElementById("prev");
var curr = document.getElementById("curr");
var allEverSelected = [ selectElem.value ];
selectElem.addEventListener("change", function(evt){
allEverSelected.push( this.value );
prev.innerHTML = allEverSelected[allEverSelected.length - 2];
curr.innerHTML = allEverSelected[allEverSelected.length - 1];
});
To access default value, just get the <select> value after DOM loads.
selected attribute on <option> tag exist only to make other than first <option> element inside <select> default option, i.e.:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
Above select's default value is 2.
I think this is the one what you want. Try it.
function onChangeOption(opt) {
var update_value = opt.value;
console.log(update_value);
var selectedValue;// = '???'; // get selected attribute
// I think this is the one you want
//If you want to select the HTML element,
selectedValue=document.querySelector("option[value='"+update_value+"']");
console.log(selectedValue);
//
if (update_value != selectedValue) {
// Do some things
}
}
//onChangeOption(document.querySelector('form'));
function start(){
while(typeof document.querySelector('form')!=typeof {}){}
onChangeOption(document.querySelector('.form-control'));
}
<body onload="start()">
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<!-- I wanna got this -->
<option value="2">2</option>
</select></body>
I have a form which has got 45 dropdownlist and I m using the bottom code for its
validation.
how can I use only one function of bottom code to do validation for all of my 45 dropdownlist ??
Here is the Function
function Validate()
{
var e = document.getElementById("dropdownlistone");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
----- HTML CODE
<select id="dropdownlistone">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onClick="Validate()" value="select"/>
This is a case when you need to use classes. Then use querySelectorAll method:
function Validate() {
var e = document.querySelectorAll(".dropdownlistone");
for (var i = 0; i < e.length; i++) {
var strUser = e[i].options[e[i].selectedIndex].value;
var strUser1 = e[i].options[e[i].selectedIndex].text;
if (strUser == 0) {
alert("Please select a user");
return;
}
}
}
Demo: http://jsfiddle.net/cwNaH/
And here is one more example with more user friendly validation messages: http://jsfiddle.net/cwNaH/1/
You can use DOM Method getElementsByTagName for select box and set an data-attr to "validate" for those whom you want to validate, if you dont want it to be validate simply don't add the above mentioned attribute.
Ex. HTML
<select id="sel1" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<select id="sel2" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
JavaScript
function validate()
{
var ele = document.getElementsByTagName("select");
for(var i=0;i<ele.length;i++)
{
if(ele.getAttribute("data-attr") && ele.getAttribute("data-attr")=='validate')
{
// you have all 47 select boxes whoose data-attr is validate
// each select box will be in ele[i]
var value= ele[i].options[ele[i].selectedIndex].value;
var text= ele[i].options[ele[i].selectedIndex].text;
alert( value+ " : " + text);
}
}
}