Shorten or simplify jQuery logic - javascript

Are there any possible method to shorten the below jQuery code section?
I may need to repeat using the same logic for the other 8 select boxes. Many thanks.
Code
$('#select_client').on('change', function() {
var val = this.value;
/* Possible to shorten this section? I have more cases like this */
if (val == 'OTHER') {
$('#input_client').addClass('show');
$('#input_client').removeClass('hide');
$('#input_client').val('');
$('#input_client').focus();
} else {
$('#input_client').addClass('hide');
$('#input_client').removeClass('show');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select class="form-control" id="select_client" name="select_client">
<option value="1">Company A</option>
<option value="2">Company A</option>
<option value="3">Company A</option>
<option value="4">Company A</option>
<option value="OTHER">Other</option>
</select>
<input id="input_client" type="text" class="form-control hide" placeholder="Please provide Client name" />

please try this
$('#select_client').on('change', function() {
var val = this.value;
/* Possible to shorten this section? I have more cases like this */
if(val=='OTHER'){
$('#input_client').addClass('show').removeClass('hide').val('').focus();
} else {
$('#input_client').addClass('hide').removeClass('show');
}
})

$('#select_client').on('change', function() {
$input = $('#input_client')
.toggleClass('show',$(this).val() ==='OTHER')
.removeClass('hide',$(this).val() !=='OTHER');
if($(this).val()==='OTHER'){
$input.val('').focus();
}
});
this is shorter... And you can add some condition to make it work the same function with multiple select-input couple ;)

Since you are using jQuery, you can chain functions to reduce redundancy for typing selector.
You can also look into .toggleClass if you wish to add/remove a class based on condition.
Also, instead of fetching the element again and again, you can save it in a variable and use this variable everywhere.
$('#select_client').on('change', function() {
var valid = this.value === 'OTHER';
var $input = $('#input_client');
$input
.toggleClass('show', valid)
.toggleClass('hide', !valid);
if (valid) {
$input
.val('')
.focus();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select class="form-control" id="select_client" name="select_client">
<option value="1">Company A</option>
<option value="2">Company A</option>
<option value="3">Company A</option>
<option value="4">Company A</option>
<option value="OTHER">Other</option>
</select>
<input id="input_client" type="text" class="form-control hide" placeholder="Please provide Client name" />

You can just use .toggle to toggle the display of your input according to conditionals.
Also if you are planning to have multiple select and input boxes to that, you should use classes instead of id.
Targeting id is not a good idea here if you have same multiple elements in your webpage.
In the below example I have used .input_client class as a selector.
$('#select_client').on('change', function() {
var val = this.value;
/* Possible to shorten this section? I have more cases like this */
if (val == 'OTHER') {
$(this).next(".input_client").toggle("display");
$(this).next(".input_client").val('');
$(this).next(".input_client").focus();
}
})
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="form-control" id="select_client" name="select_client">
<option value="1">Company A</option>
<option value="2">Company A</option>
<option value="3">Company A</option>
<option value="4">Company A</option>
<option value="OTHER">Other</option>
</select>
<input id="input_client" type="text" class="input_client form-control hide" placeholder="Please provide Client name" />

Related

add value to input field automatically

How to add values automatically without add button? Just select value from dropdown and do it again and again to add them to the same input like on image.
html
<select name="programs_dropdown" id="programs_dropdown">
<option value="php">php</option>
<option value="jquery">jquery</option>
<option value="html" selected="selected">HTML</option>
</select>
<div id="add">Add</div>
<input type="text" name="programs_input" id="programs_input" />
jquery
$(document).ready(function(){
$('#add').click(function() {
var program = $("#programs_dropdown").val(); //get value of selected option
var programs = $('#programs_input').val().split(",");
if (programs[0] == "") {
programs.pop()
}
if ($.inArray(program, programs) == -1) {
programs.push(program);
}
$('#programs_input').val(programs.join(',')); //add to text input
});
});
You could make use of the .change() function in jQuery to fire your function whenever changes are made to your <select> element. You could then fetch the .val() from that and store it into a variable. You can then append() an input field with the value that you just stored to a container. Note that you will also need to use concatenation, as you will be exiting your string parameter for the append function to concatenate your drop down value. Concatenation in JavaScript is done by the use of +.
Example of concatenation in use that you will need:
$("#inputContainer").append("<input type='text' value='"+selectValue+"' /><br />");
Full example code to your question:
$( "#programs_dropdown" ).change(function() {
var selectValue = $(this).val();
if(selectValue != "default"){
$("#inputContainer").append("<input type='text' value='"+selectValue+"' /><br />");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="programs_dropdown" id="programs_dropdown">
<option value="default" selected="selected">select value</option>
<option value="php">php</option>
<option value="jquery">jquery</option>
<option value="html">HTML</option>
</select>
<br />
<br />
<div id="inputContainer"></div>
I think This is the answer which you are looking for!
HTML
<select class="my-select-class">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>
<br />
<br />
<input type="text" class="my-input-class">
JQuery
var allSelected = [];
$(document).ready(function(){
$(".my-select-class").on("change", function(){
let val = $(this).val();
let index = allSelected.indexOf(val);
if (index > -1) allSelected.splice(index, 1);
else allSelected.push(val);
$(".my-input-class").val(allSelected.join());
});
});
You can play around with JQuery change event and get the result which you wanted.

How to Display Select Tag using 'change' jquery 2.1.4?

I am trying to display select box when user input some values in the textbox , I tried using onchange property of jquery but its not working.
Below is my code
$(document).ready(function() {
$("#total_enter").change(function() {
$(".gst_sel_wrap").css("display", "block");
});
})
.gst_sel_wrap {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>
Try using the jQuery keydown method: https://api.jquery.com/keydown/
I also added some code to hide the dropdown in the beginning, so the effect becomes obvious.
$(document).ready(function(){
$(".gst_sel_wrap").hide();
$("#total_enter").keydown(function(){
$(".gst_sel_wrap").show();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>
You can use either keyup or keydown or both as I do here:
$(document).ready(function() {
$("#total_enter").on("keyup keydown",function() {
$(".gst_sel_wrap").css("display", "block");
});
})
.gst_sel_wrap {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>
To achieve this you can use the input event, as it fires when a key is pressed and also when a value is copy/pasted in. You should also check the value of the element to ensure that it isn't empty, as the value can be deleted, when I would assume your select should be hidden again.
Finally, note that you can use toggle() to hide or show the select based on the given value, in a more succinct way. Try this:
$(document).ready(function() {
$("#total_enter").on('input', function() {
$(".gst_sel_wrap").toggle(this.value.trim() != '');
});
})
.gst_sel_wrap {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>

Javascript change input value when select option is selected

I am very new to javascript. So i have a select option and an input field. What i want to achieve is to have the value of the input field change when i select a particular option. This is what i have tried:
First Name: <input type="text" value="colors">
<select name="">
<option>Choose Database Type</option>
<option onclick="myFunction(g)>green</option>
<option onclick="myFunction(r)>red</option>
<option onclick="myFunction(o)>orange</option>
<option onclick="myFunction(b)>black</option>
</select>
<script>
function myFunction(g) {
document.getElementById("myText").value = "green";
}
function myFunction(r) {
document.getElementById("myText").value = "red";
}
function myFunction(o) {
document.getElementById("myText").value = "orange";
}
function myFunction(b) {
document.getElementById("myText").value = "black";
}
</script>
A few things:
You should use the onchange function, rather than onclick on each individual option.
Use a value attribute on each option to store the data, and use an instance of this to assign the change (or event.target)
You have no ID on your text field
You're missing the end quote for your onclick function
<select name="" onchange="myFunction(event)">
<option disabled selected>Choose Database Type</option>
<option value="Green">green</option>
<option value="Red">red</option>
<option value="Orange">orange</option>
<option value="Black">black</option>
</select>
And the function:
function myFunction(e) {
document.getElementById("myText").value = e.target.value
}
And add the ID
<input id="myText" type="text" value="colors">
Fiddle: https://jsfiddle.net/gasjv4hs/
More proper way is to put your JS code in a different .js file and use Jquery as when you go further with your programming this is the proper way.
Your HTML
<input type="text" id="color" name="color">
<select name="" id="changeData">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
Your JS
$(document).ready(function () {
$('#changeData').change(function(){
var color = $(this).val();
$('#color').val(color);
})
});
Also make sure that you have added Jquery Library to your Project. You can either download Jquery and add in your project folder OR also you can use CDN. in this example CDN is used.
I came up with a similar problem. In my case i was trying to change the minimum value of an input based on the value of an option in a select list. I tried to apply the above solutions but nothing worked. So i came with this, which can be applied to problems similar to this
HTML
<input id="colors" type="text" value="">
<select id="select-colors" name="" onchange="myFunction()">
<option disabled selected>Choose Colour</option>
<option value="green">green</option>
<option value="red">red</option>
<option value="orange">orange</option>
<option value="black">black</option>
</select>
JS
function myFunction() {
var x = document.getElementById("select-colors").value;
document.getElementById("colors").value = x;
}
This works by getting the value of the select with id "select-colors" on every change, assigning it into a variable "x" and inserting it into the input value with id "colors". This can be implemented in anyway based on your problem
You create functions with same name multiple times.
Only last one will work.
the variables you pass g,r,o,b are undefined.
Don't add onclick to option add onchange to select.
Make use of HTML5 data-* attribute
function myFunction(element) {
document.getElementById("myText").value = element;
}
First Name: <input type="text" id="myText" value="colors">
<select name="" onchange="myFunction(this.value);">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
You can resolve it this way.
` First Name:
<select name="" onchange="myFunction()" id="selectID">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script>
function myFunction() {
var selectItem = document.getElementByID('selectID').value;
document.getElementByID('yourId').value = sekectItem;
}
</script>
Here's a way to achieve that:
var select = document.getElementById('colorName');
function myFunction(event) {
var color = 'No color selected';
if (select.selectedIndex > 0) {
color = select.item(select.selectedIndex).textContent;
}
document.getElementById('myText').value = color;
}
select.addEventListener('click', myFunction);
myFunction();
First Name: <input type="text" id="myText">
<select id="colorName">
<option>Choose Database Type</option>
<option>green</option>
<option>red</option>
<option>orange</option>
<option>black</option>
</select>
Your code should be like following.
<input type="text" name="color" id="color">
<select name="" id="change_color">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function () {
$('#change_color').change(function(){
var color = ($(this).val());
$('#color').val(color);
})
});
</script>
Here is JS Code that worked for me
var selectYear = document.getElementById('select-year');
selectYear.addEventListener('change', function() {
var selectedYear = document.getElementById('selected-year');
selectedYear.innerHTML = selectYear.value;
});
Select Input ID: select-year
Text ID: selected-year
Code generated from Codex AI :)

select 2 + get value on click

I am facing a issue that I want the select value on click event. i tried with change event but I get all values comma separated instead of current value.
What I want to do is, Suppose there are multiple options with a All option. So if a user select All option then it should clear all selected option and only All option will display.
I have tried below codes
$(".chzn-select").on('select2:selecting', function () {
var st = ($(this).select2('val'));
}
it show null on first click.
And
$(".chzn-select").on('change', function () {
var st = ($(this).select2('val'));
}
show all values in comma separated format. There is no example I found of onclick event with select2 JS. Here is the list of events
HTML
<select name="country[]" multiple="" data-placeholder="Select country" class="form-control chzn-select" required="required" id="country">
<option disabled="disabled" value="1">Abu Dhabi</option>
<option value="2">Dubai</option>
<option disabled="disabled" value="3">Singapore</option>
<option disabled="disabled" value="4">Thailand</option>
<option value="8">Afghanistan</option>
<option value="All">All</option>
</select>
Here is the jsfiddle
https://jsfiddle.net/bayahiassem/gtew005w/11/
$(".chzn-select").select2({selectOnClose: true}).on("select2:selecting", function(evt) {
if(evt.params.args.data.id == 'All') {
$(".chzn-select").val(null).trigger("change");
} else {
$('.chzn-select > option[value=All]').prop("selected", false);
}
});
I didn't get you.
If i correct.
$(this).select2('val').find(':selected');
Here you are. It will you give the current selected item(s) - hold ctrl for multiple selections
$(function () {
$(".chzn-select").on('change', function (evt) {
$('#selected').text('Selected: ' + ($(this).val()))
})
})
select {
width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="country[]" multiple="" data-placeholder="Select country" class="form-control chzn-select" required="required" id="country">
<option disabled="disabled" value="1">Abu Dhabi</option>
<option value="2">Dubai</option>
<option disabled="disabled" value="3">Singapore</option>
<option disabled="disabled" value="4">Thailand</option>
<option value="8">Afghanistan</option>
<option value="All">All</option>
</select>
<div id="selected"></div>
I hope this will work,
$(".chzn-select").select2({selectOnClose: true});
$(".chzn-select").on("select2:select", function (evt) {
if($.inArray('All',$(this).val()) != -1){
$(this).val('All').trigger("change");
}
});
Replace your js code with this, it will work.
Here is jsfiddle link for working code.

How to use if else statements in select form?

In my registration page, I'm gonna use two drop-down select that one of them should be hidden if its Negative and if its positive new drop-down will open to choose ...
In mysql table I've table as diabetes name with enom
enum('negative', 'insulin', 'drug', 'ndm', 'mody', '')
Here's my code:
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
For example: If Diabetes is negative value is negative as default then Diabetes Type is hidden
and
If Diabetes is positive then Diabetes type will be appeared to choose items.
those values like insulin, drug, mdm, mody should be inserted into this:
value="positive"
How can I make it through java script?
I can't add class or div or span. Is it possible just through JavaScript using ??
Thank you so much
Use jquery, it is comparatively easier.
$(document).ready(function(){
$("#diabetestype").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").show();
}else{
$("#diabetestype").hide();
}
});
});
To make this code workable, you need to add value of Positive option also. So instead value="" change it to value="positive".
You can even hide the label also:
$(document).ready(function(){
$("#diabetestype").closest("div").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").closest("div").show();
}else{
$("#diabetestype").closest("div").hide();
}
});
});
<div><label for="diabetes">Diabetes:</label>
<select id="diabet" name="diabet" onchange="checkDiabet();">
<option value="negative">Negative</option>
<option value="positive" id="isDiabet">Positive</option>
</select>
</div>
<div id="type" style="display: hidden;">
<label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
<script>
function checkDiabet() {
var isDiabet = document.getElementById("isDiabet").selected;
if (isDiabet == true) { document.getElementById("type").removeAttribute("style"); }
else { document.getElementById("type").style.display = "none"; }
}
</script>
First, set the first select to fire the function checkDiabet() by the attribute onchange. Then give the option an id, which needs to be checked, so you can access it easily.
Then, set the second select to display: none This could be done in a CSS header or file, or like in this case inline. (div style=""), also add an id to access it easily. (div id="type")
Now comes the function checkDiabete(). It checks if the select is selected (can be true or false (bool)). Is selected => show (div id="type"), if not, hide this div (and all of it's contents)
(if is already hidden, it then overwrites the (style="display: none;") with (style="display: none;))
That's it! :)
Try this:
function SelectDiabetes() {
var d = document.getElementById("diabetes").value;
var dType = document.getElementById("diabetestypebox");
if(d == "negative")
dType.style.display = "none";
else
dType.style.display = "block";
}
SelectDiabetes();
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="SelectDiabetes(this.value);">
<option value="negative">Negative</option>
<option value="positive">Positive</option>
</select>
</div>
<div id="diabetestypebox"><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Call a js function onchange of select id diabetes
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="toggleTypes()">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" style="display:none" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Use the following javascript
function toggleTypes(){
var el=document.getElementById('diabetes');
var medElem=document.getElementById('diabetestype');
if(el.value=='positive') {
medElem.style.display='block';
} else {
medElem.style.display='none';
}
}

Categories

Resources