jQuery - How to pass 'this' to a function? [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
How do I pass $(this) into a function. In my example below I want to populate the address textbox with the value of the selected drop-down option label but only if the value selected is not empty.
The following doesn't work?
$("#AddressId").change(function () {
$("#Address").val(function(index, val) {
val = $(this).val();
return val === "" ? "" : $('option:selected', this).text();
}, this).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
<option value="">-- Please select --</option>
<option value="1">xyz street</option>
...
</select>
<input id="Address" name="Address" value="" type="text">

To achieve this store the this reference of #AddressId in a variable the change event handler. You can then use that variable in the inner val() function, like this:
$("#AddressId").change(function() {
var $addressId = $(this);
$("#Address").val(function(index, val) {
val = $addressId.val();
return val === "" ? "" : $('option:selected', $addressId).text();
}, this).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
<option value="">-- Please select --</option>
<option value="1">xyz street</option>
</select>
<input id="Address" name="Address" value="" type="text">
Although note that the function you provide to val() is not required, and is the cause of your problem. You can simplify the code to just this:
$("#AddressId").change(function() {
var address = $(this).val() ? $(this).find('option:selected').text() : '';
$("#Address").val(address).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
<option value="">-- Please select --</option>
<option value="1">xyz street</option>
</select>
<input id="Address" name="Address" value="" type="text">

You could simply add a condition selected_value != "" then assign the selected value if isn't empty :
$("#AddressId").change(function () {
var selected_value = $(this).val();
if( selected_value != ""){
$("#Address").val( selected_value );
}
});
Hope this helps.
$("#AddressId").change(function () {
var selected_value = $(this).val();
if( selected_value != ""){
$("#Address").val( selected_value );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
<option value="">-- Please select --</option>
<option value="1">xyz street</option>
<option value="2">abc street</option>
<option value="3">def street</option>
</select>
<input id="Address" name="Address" value="" type="text">

I bet you have just overcomplicated it.
$("#AddressId").change(function() {
if ($(this).val()) {
$('#Address').val($(this).find('option:selected').text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
<option value="">-- Please select --</option>
<option value="1">xyz street</option>
...
</select>
<input id="Address" name="Address" value="" type="text">

Related

Select datalist value on input change and populate the form using jQuery javascript

I am trying to do autocomplete, when input is changed and an option is selected from the datalist, then I want the form and text field to be populated with selected value/text from the datalist.
I tried many options from similar questions here on stackexchange, but not able to make it work.
Help!
$(document).ready(function() {
$('#UserCity').on('input', function() {
var str = "";
console.log($(this).val());
$("#UserCitySelect").on('select', function() {
str += $(this).text() + " ";
});
str = $("#UserCitySelect option:selected").text()
console.log(str);
document.getElementById("selected").text = str;
document.getElementById("selecteddiv").innerHTML = str;
console.log($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="UserCity" id="UserCity" label="User City" max_length="25" list="UserCitySelect" required="">
<p id="selected"><p>
<div id="selecteddiv"><div>
<datalist id="UserCitySelect">
<option value="Los Angeles">Los Angeles</option>
<option value="New York">New York</option>
<option value="Chicago">Chicago</option>
</datalist>
:selected does not work on datalist options, as one datalist can provide suggestions for multiple inputs. If two different inputs contain two different suggestions from the list, which would be the selected one?
you can check the value of the input on change with event of input text and assign the value in div with the id.
$(document).ready(function() {
$("input[name='UserCity']").on('input', function(e){
var selectedVal = $(this).val();
document.getElementById("selected").innerHTML = selectedVal ;
document.getElementById("selecteddiv").innerHTML = selectedVal ;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="UserCity" id="UserCity" label="User City" max_length="25" list="UserCitySelect" required="">
<datalist id="UserCitySelect">
<option value="Los Angeles">Los Angeles</option>
<option value="New York">New York</option>
<option value="Chicago">Chicago</option>
</datalist>
<p id="selected"></p>
<div id="selecteddiv"><div>

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 can I pass a value from input field to a select option using jquery?

I'm using the following code to pass a value from a select option to a given input field.
$(".itemconditionmenu").change(function() {
var conditionofitem = $(this).val();
$("#meta_itemcondition").val(conditionofitem);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select id="itemcondition" class="itemconditionmenu">
<option value="">Choose Condition</option>
<option value="New">New</option>
<option value="Used">Used</option>
</select>
<input id="meta_itemcondition" type="text" value="New">
But how can I pass the value of the input field back to the select option value using jQuery?
I am not sure what you are exactly looking, however, as per my understanding I have modifed your code samples.. You can check below snippet.
$( document ).ready(function() {
var conditionofitem = $("#meta_itemcondition").val();
$(".itemconditionmenu").val(conditionofitem);
});
$(".itemconditionmenu").change(function() {
var conditionofitem = $(this).val();
if(conditionofitem == '') {
$("#meta_itemcondition").val('Choose Condition');
} else {
$("#meta_itemcondition").val(conditionofitem);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select id="itemcondition" class="itemconditionmenu">
<option value="">Choose Condition</option>
<option value="New">New</option>
<option value="Used">Used</option>
</select>
<input id="meta_itemcondition" type="text" value="New">
Please check and let me know if you have any further queries.
Try this
$("#addOption").click(function(){
$("#itemconditionmenu").append('<option value="'+$("#meta_itemcondition").val()+'" selected="selected">'+$("#meta_itemcondition").val()+'</option>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="itemconditionmenu">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input id="meta_itemcondition" type="text" value=""></input>
<button id="addOption">ADD</button>
Example for the same: Blur out your input and value option will be added to select dropdown
$(".itemconditionmenu").change(function() {
var conditionofitem = $(this).val();
$("#meta_itemcondition").val(conditionofitem);
});
$("#meta_itemcondition").blur(function() {
var inputValue = $(this).val();
var o = new Option(inputValue, inputValue);
$(o).html(inputValue);
$("#itemcondition").append(o);
$("#itemcondition").val(inputValue);
});
$( document ).ready(function() {
var value = $("#meta_itemcondition").val();
console.log(value)
var alreadyOption = false;
$("#itemcondition option").each(function()
{
alreadyOption = $(this).val() === value;
if(alreadyOption) {
$("#itemcondition").val(value);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<select id="itemcondition" class="itemconditionmenu">
<option value="">Choose Condition</option>
<option value="New">New</option>
<option value="Used">Used</option>
</select>
<input id="meta_itemcondition" type="text" value="New"/>
Here you can find inline functionality
if you enter a value in textbox value append in drop-down
if you select drop-down value auto set in textbox.
Note: add value in textbox change just input focus
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="jsSelect" onchange="$('.jsTextBox').val($(this).val())">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input class="jsTextBox" onchange="if($(this).val()!=''){$('.jsSelect').append($('<option></option>').attr('value',$(this).val()).text($(this).val()));$('.jsSelect').val($(this).val());}" type="text" value="">

Javascript - Make an element dissapear if an option is selected

I have a list of countries in a drop-down menu
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1">USA</option>
<option value="2" selected="">Canada</option>
<option value="3">Rest of the World</option>
<p><input type="text" name="state_field" value="" id="state"></p>
My goal is: If value 3 is selected, the input field "state" disappears. If option 1 or 2 are selected, it should show the field "state".
In case the user has already entered a value in the input field "state" (because option 1 or 2 were previously selected) and he changes it to option 3, the code should first erase the value entered in the state field and then make that field disappear.
How would the Javascript code look like?
I appreciate your help!
UPDATE:
Apparently there is a function already running "onchange", so that the HTML looks this way:
<select name="<select name="country_List" onchange="checkCountry();" id="countries">
<option value="">––> Select</option>
<option value="1">USA</option>
<option value="2">Canada</option>
<option value="3">Mexico</option>"
<option value="4">Argentina</option>"
<option value="5">Australia</option>"
</select>
This seems to be interfering with the codes suggested for this case. Is it there any way to run the code to hide the "state" after the "onchange" function "checkCountry()" has been run?
First you need to validate your html; you're missing a closing </select> tag. Second, the textbox has to be disabled when not required so that it is not included in the form data when the form is submitted. The following should meet your requirements:
$('#countries').on('change', function() {
if( $.trim( this.value ) === '3' ) {
$('#state').val('').prop('disabled', true).closest('p').hide();
} else {
$('#state').prop('disabled', false).closest('p').show();
}
});
$('#countries').on('change', function() {
if( $.trim( this.value ) === '3' ) {
$('#state').val('').prop('disabled', true).closest('p').hide();
} else {
$('#state').prop('disabled', false).closest('p').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1">USA</option>
<option value="2" selected="">Canada</option>
<option value="3">Rest of the World</option>
</select>
<p><input type="text" name="state_field" value="" id="state"></p>
UPDATE
And this should meet your updated requirements; you would just update the logic so you end up with the least number of clauses or boolean expressions in the if condition:
$('#countries').on('change', function() {
if( $.trim( this.value ) === '2' || $.trim( this.value ) === '1') {
$('#state').prop('disabled', false).closest('p').show();
} else {
$('#state').val('').prop('disabled', true).closest('p').hide();
}
})
.change();
$('#countries').on('change', function() {
if( ['1','2'].indexOf( this.value ) > -1 ) {
$('#state').prop('disabled', false).closest('p').show();
} else {
$('#state').val('').prop('disabled', true).closest('p').hide();
}
})
.change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1">USA</option>
<option value="2" selected="">Canada</option>
<option value="3">Rest of the World</option>
</select>
<p><input type="text" name="state_field" value="" id="state"></p>
Please note that .change() triggers the change event when the page loads so that if the value is not 1 or 2, the textbox will be hidden.
in javascript:
<script>
function show(mode)
{
document.getElementById('state').style.visibility = (mode) ? 'visible' : 'hidden';
}
<script>
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1" onclick="show(true)">USA</option>
<option value="2" onclick="show(true)">Canada</option>
<option value="3" onclick="show(false)">Rest of the World</option>
<p><input type="text" name="state_field" value="" id="state"></p>
JSFIDDEL
$( "select#countries" )
.change(function () {
if($("select#countries option:selected").attr("value")=="3"){
$("select#countries").hide();
$("#state").show();
$("#state").val($("select#countries option:selected").text());
}else{
$("#state").hide();
$("select#countries").show();
$("#state").val("");
}
});
$( "#state" )
.change(function () {
if($("#state").val()==""){
$("#state").hide();
$("select#countries").show();
}else{
}
});
JSFIDDEL

Drop down text input option

I want a drop down element where user can select from available options or select enter value option which in turn allows to enter value.
I specifically want that user can enter value only when they select "Enter a value " option.
Here is what I have tried so far.
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
} else {
x.find('.holder').val(x.find('option:selected').text());
}
});
JS fiddle
however it wont work properly if i click the enter value option again.
I think there are many plugins that do what you want but if you want to create your own, it's a basic and simple solution.
You can create a select and a textbox with display:none like this:
<select id="ddlDropDownList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="-1">Enter Value</option>
</select>
<input id="txtTextBox" type="text" />
<style>
#txtTextBox{
display:none;
}
</style>
then try this JQuery:
$("#ddlDropDownList").change(function(){
if($(this).val() == '-1'){
$("#txtTextBox").fadeIn();
}else{
$("#txtTextBox").fadeOut();
}
});
Check JSFiddle Demo
I have forked your JSFiddle to http://jsfiddle.net/pwdst/4ymtmf7b/1/ which I hope does what you wanted to achieve.
HTML-
<div class="ginput_container">
<label for="input_1_4">Select option</label>
<select class="medium gfield_select" id="input_1_4" name="input_4" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<div>
<label class="hidden-label" for="input_1_4_other">Other value</label>
<input class="holder" id="input_1_4_other" disabled="disabled" name="input_1_4_other" placeholder="None" type="text" />
</div>
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var $this = jQuery(this);
var val = $this.val();
var holder = $this.parent().find('.holder');
if (val === "*"){
holder.val('');
holder.removeAttr('disabled');
holder.focus();
} else {
holder.val(this.options[this.selectedIndex].text);
holder.attr('disabled', 'disabled');
}
});
When the "Enter value" option is chosen then the input box is enabled, value set to an empty string, and it is focused. If another option is chosen then the text input is disabled again, and the text value from the select list is used.
Thanks guys
I guess i have found my answer
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
jQuery(this).val("0"); // Change select value to None.
} else {
x.find('.holder').val(x.find('option:selected').text());
x.find('.holder').prop('disabled',true);
}
});
JS FIDDLE

Categories

Resources