Javascript: Dynamically add fields from a select input with a button - javascript

i need to add dynamically fields from a list values, i have this one:
HTML:
<select name="list">
<option>Select One</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
JS:
$("[name=list]").on("change", function (e) {
var val = $(this).val();
if (val.length > 0) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
This works fine, but i want to add a "Add field" button to do this, how i can do that?

Its just simple. Instead of writing your code into onchange, you bind it to click event of your button.
For example, say you have button with id - #addField. Your click event for button would be
$("#addField").on('click',function(){
var val = $("[name=list]").val(); //get the selected val from select element
if (val.length) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});

You will move the logic of the .change() event of select to the .click() event of the button.
something similar to:
$("#btnId").on("click", function (e) {
var val = $("[name=list]").val();
if (val.length > 0) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
where btnId is the id of the button

try this : https://jsfiddle.net/qact415y/
<select id="list">
<option>Select One</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
// enter the text you want to add to the combo
<input type="text" id="input"/>
<button name="add">Add</button>
$("[name=list]").on("change", function (e) {
var val = $(this).val();
if (val.length > 0) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
$("[name=add]").on("click", function (e) {
console.log("add");
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = document.getElementById("input").value;
x.add(option);
});

Related

Filter <SELECT> options based on value

I have 2 input selects
Country and Cars
This is the structure: [https://jsfiddle.net/CornerStone20/r1eanhwv/6/][1]
JSFIDDLE: [1]: https://jsfiddle.net/CornerStone20/r1eanhwv/6/
When I select Country, How do I only show the selected country's cars?
I have tried:
$(function() {
$('#Country_Select').on('change', function() {
var val = this.value;
$('#Cars_Select option').hide().filter(function() {
return this.value.indexOf( val + '_' ) === 0;
})
.show();
})
.change();
});
You can use each loop to iterate through options and check if the value of car select- box is same as country select-box depending upon this show() or hide() options .
Demo Code :
$(function() {
$('#Country_Select').on('change', function() {
var val = this.value;
$('#Cars_Select option').each(function() {
//checking value of opton in cars selct is same
if ($(this).val() == val) {
$(this).show(); //show it
} else {
$(this).hide(); //hide other
}
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
// Country select
<select id="Country_Select" class="form-control">
<option selected="true" disabled="false">Choose Country</option>
<option value="0001">France</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Germany</option>
<option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">New Zealand</option>
</select>
// Cars
<select id="Cars_Select" class="form-control">
<option selected="true" disabled="false">Choose Cars</option>
<option value="0001">Renauld</option>
<option value="0001">Mini</option>
<option value="0001">Paris</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">BMW</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Audi</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Mercedes</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Benz</option>
<option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">Kiwi Auto</option>
</select>
Even though the question has been answered, I am writing a better approach here:
$('#Country_Select').on('change', function(e) {
let cars = $('#Cars_Select').children();
cars.hide();
let country = $(this).val();
cars.filter('[value=' + country + ']').add(cars.eq(0)).show();
});

drop-down validation and Combine If statement on JavaScript with extra condition for validation?

I have a function to check if the value meet the requirement, it is working fine so I have another drop-down(select) to validate with same condition but the drop-down values different I am only checking the blank selection.
Goal:
any way to improve the JS or combine them correctly.
Many thanks in advance
// for 1st drop down
function checkPrimeSelectChangeValue() {
var selObj = document.getElementById("dropdown1");
var selValue = selObj.options[selObj.selectedIndex].value;
if (selValue == "") { // if blank is selected add css for validation
$("#dropdown1").attr('disabled', 'disabled');
$("#dropdown1").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown1"); // remover error
}
return;
}
// 2nd dropdown like below
function checkSecondSelectChangeValue() {
var selObj2 = document.getElementById("dropdown2");
var selValue2 = selObj.options[selObj.selectedIndex].value;
if (selValue2 == "") { // if blank is selected add css for validation
$("#dropdown2").attr('disabled', 'disabled');
$("#dropdown2").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown2"); // remover error
}
return;
}
// Can I do this or Any ipmorvent can be done to this
function checkCombinedSelectChangeValue() {
var selObj = document.getElementById("dropdown1");
var selObj2 = document.getElementById("dropdown2");
var selValue = selObj.options[selObj.selectedIndex].value;
var selValue2 = selObj.options[selObj.selectedIndex].value;
if (selValue == "") { // if blank is selected add css for validation
$("#dropdown1").attr('disabled', 'disabled');
$("#dropdown1").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown1"); // remover error
}
return;
if (selValue2 == "") { // if blank is selected add css for validation
$("#dropdown2").attr('disabled', 'disabled');
$("#dropdown2").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown2"); // remover error
}
return;
}
<p>1st dropdown1 </p>
<select name="test" id="select">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
<br>
<p>2nd dropdown1 </p>
<select name="test" id="select2">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
I optimized your function a little, assuming it's supposed to run when your select changes. I also assume that you want to add the disabled property to your #btnUpdateForm since that isnt really clear with the code you provided.
First add the disabled property to your Update button like this:
<button id="btnUpdateForm" disabled>Update</button>
HTML:
<p>1st dropdown1 </p>
<select class="dropdown" name="test" id="select">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
<br>
<p>2nd dropdown1 </p>
<select class="dropdown" name="test" id="select2">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
JQuery:
$('.dropdown').change(function() {
var val1 = $('#select').val();
var val2 = $('#select2').val();
if (val1 == '' || val2 == '') {
$('#btnUpdateForm').prop('disabled', true);
if (val1 == '') {
$('#dropdown1').addClass('text-error');
if (val2 !== '') {
$('#dropdown2').removeClass('text-error');
}
}
else if (val2 == '') {
$('#dropdown2').addClass('text-error');
if (val1 !== '') {
$('#dropdown1').removeClass('text-error');
}
}
}
else {
$('#btnUpdateForm').prop('disabled', false);
$('#dropdown1').removeClass('text-error');
$('#dropdown2').removeClass('text-error');
}
});
Basically now the Error will show up for each Dropdown with value="" and the button will only be enabled when both Dropdown's value isn't 0.

How to get the value of option with attribute selected

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>

Trigger event when selecting in a dropdown javascript eventlistener

I have this javascript function,
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if("Blank Test" === e.selectedIndex){ alert("yo"); }
}
}
My problem is how to trigger the function when selected the same value of dropdown list?
I tried this code,
document.getElementById("list").addEventListener("change",listQ);
And it must use an event listener.
You can use the onchange method on your select element.
var changedText = document.getElementById('changed');
function listQ(){
changedText.textContent = this.value;
}
document.getElementById("list").onchange = listQ;
For this HTML
<select id="list">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<p>
Your value <span id="changed"></span>
</p>
Here is a Fiddle forked from Jonathan, and here is MDN documentation for the change event.
The line "Blank Test" isn't going to work because e.selectedIndex is going to be an index (a number). You could use e.options[e.selectedIndex].value
Apart from that, just change the event listener to "click" instead of "change":
<select id="list">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="Blank Test">Four</option>
</select>
<script type="text/javascript">
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if("Blank Test" === e.options[e.selectedIndex].value){ alert("yo"); }
}
}
document.getElementById("list").addEventListener("click",listQ);
</script>
Here's a Fiddle to demonstrate: https://jsfiddle.net/h81pcpm0/
I've solved your problem here: https://jsfiddle.net/evL4cc5q/
var lastIndex = "";
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if(e.selectedIndex != lastIndex) {
if("Blank Test" === e.options[e.selectedIndex].value)
alert("yo");
lastIndex = e.selectedIndex;
}
else {
lastIndex = "";
}
}
}
document.getElementById("list").addEventListener("click",listQ);

Can I pass multiple Id's inside a document.getelementbyID?

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);
}
}
}

Categories

Resources