Combine input and select input/change - javascript

I have two input fields and two select fields.
I do some frontend validation on input of the input fields and when I change the select of the select fields ... for ALL fields.
The only way I get this to work is if I split it like this:
var is_currencyBilling;
var is_countryBilling;
var is_cityBilling;
var is_postalBilling;
$('#cityBilling,#postalBilling').on('input', function () {
...
});
$('#currencyBilling,#countryBilling').on('change', function () {
...
});
Is there any way to combine this? Or do I have to split it like above?
Edit:
If I combine it in a change like this:
$('#cityBilling,#postalBilling,#currencyBilling,#countryBilling').on('change', function () {
console.log('Test');
...
});
... it works after I tab to another input field or a input field looses focus. But is there any chance to keep the former validation behaviour right when I 'change' the value of an input field?

You can use same change event for all or use multiple events like $(selectors).on('change input', validate)
But you can also listen for different events that use the same event handler.
Within that handler your business logic can adapt to the event type or element type or whatever other special conditions you need
Basic example
$('input:text').on('input', validate);
$('input:checkbox').on('click', validate)
$('select').on('change', validate);
function validate(evt) {
console.clear()
var $el = $(this),
val = $el.val();
console.log(evt.type + ' event on: ' + this.name + ', new value is: ', val);
if ($el.is('input:text')) {
console.log('This is an input:text');
} else if ($el.is('select')) {
console.log('This is a select');
}else if ($el.is('input:checkbox')) {
console.log('Checkbox is checked = ', this.checked)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Inp1: <input name="input_one" type="text" /> Inp2: <input name="input_two" type="text" /> <br><br>
Check<input name="check_one" value="one" type="checkbox">
<br><br>
Sel 1
<select name="sel_one">
<option></option>
<option value="1">one</option>
<option value="2">two</option>
</select>
Sel 2
<select name="sel_two">
<option></option>
<option value="1">one</option>
<option value="2">two</option>
</select>

Related

How to trigger the change event on the input when I choose the option from select using jQuery?

I use jQuery to trigger an event in my project. I want to trigger an input event change when I choose an option from the select and when I choose an option the input value will be changed with the option value and show the length of the new value.
Also, I want to trigger an event change in the input but it does not work for me, I try many times but does not work :
$(document).ready(function() {
var oldVal;
var checkLength = function(val) {
$('label').html(val.length);
}
$('input').bind('change textInput input', function() {
var val = this.value;
if (val !== oldVal) {
oldVal = val;
checkLength(val);
}
});
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
str += $(this).text() + " ";
});
$("input").val(str);
})
});
This is how I would have done that.
Add change event listeners on both.
Update input with the value selected in select tag
Trigger change event from there
$("#s").change(function(){
console.log("Option selected");
$("#d").val($(this).val());
$("#d").trigger("change");
});
$("#d").change(function(){
console.log("input modified")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="d" />
<select id="s">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Try manually triggering the change event of input like this
*$( "input" ).trigger("change");*

Input box + select list + links

Why is this list not working?
I need to combine three things: input box + select list + links.
This is my attempt:
<input type="text" name="example" list="lemmas">
<datalist onChange="window.location.href=this.value" id="lemmas">
<option value="http://pastebin.com/embed_iframe/37CVfR9Z">A</option>
<option value="http://pastebin.com/embed_iframe/1kJWwbnz">a day</option>
</datalist>
Please help me to get a combo of this three things. After using the input box to select an option of the list and pressing ENTER the list has to open the link.
Thanks.
The following select works. I only need to add an input box to it:
<select onChange="window.location.href=this.value">
<option value="http://pastebin.com/embed_iframe/37CVfR9Z">A</option>
<option value="http://pastebin.com/embed_iframe/1kJWwbnz">a day</option>
</select>
This is my first time reading about <datalist/> tag. It doesn't seem to have good browser support.
Anyways... you can attach an oninput event handler to your <input/> field. I don't like using event attributes, so I am attaching the event in the JavaScript.
example.oninput = function () {
window.location.href = this.value;
}
<input type="text" name="example" id="example" list="lemmas">
<datalist id="lemmas">
<option value="http://pastebin.com/embed_iframe/37CVfR9Z">A</option>
<option value="http://pastebin.com/embed_iframe/1kJWwbnz">a day</option>
</datalist>
Side-remark - you should probably add logic to verify that the value is a URL though...
The code below should work accurately. Check the jsFiddle. I added an id="autocomplete" to the input field, jQuery checks when ENTER key is pressed in the field and based on that it redirects the page.
Revised answer with ENTER key press event:
$(function(){
// check for key press event
$('#autocomplete').keypress(function (e) {
var key = e.which;
var url = $(this).val();
// the enter key code
if(key == 13) {
if (url) { window.location = url; }
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete" name="example" list="lemmas">
<datalist id="lemmas">
<option value="http://pastebin.com/embed_iframe/37CVfR9Z">A</option>
<option value="http://pastebin.com/embed_iframe/1kJWwbnz">a day</option>
</datalist>
Alternately you could also use on input change (without ENTER key press):
$('#autocomplete').on('input', function(e) {
var url = $(this).val();
if (url) { window.location = url; }
return false;
});

Set attribute to readonly when dropdown value is changed

I have this dropdown that has 4 options.
What I want to achieve is to change the attribute of input text number to readonly when a user selects option3 or option4 from the dropdown.
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" name="number">
This is the script that I have for now, what it does is just alert the selected value.
$(document).ready(function () {
$("#s_id").change(function () {
var x = $(this).val();
alert($(this).val());
if (x == opel) {
alert("iff");
$(this).attr("readOnly", "true");
}
});
});
JS Fiddle link
Any idea/s would be really appreciated!
Use prop to make readonly and remove it back
DEMO
$(document).ready(function () {
$("#s_id").change(function () {
if (this.value === 'option3' || this.value === 'option4')
$("input[name='number']").prop('readonly', true);
else
$("input[name='number']").prop('readonly', false);//enable it back again
});
});
You can simply check your .value in your change handler and use jQuery .prop method:
$("#s_id").change(function () {
var isReadonly = (this.value === 'option3' || this.value === 'option4');
$("input[name='number']").prop('readonly', isReadonly);
});
or using an array for making it easier to modify it in future:
$("#s_id").change(function () {
var isReadonly = ['option3', 'option4'].indexOf(this.value) > -1;
$("input[name='number']").prop('readonly', isReadonly);
});
Here is the working JSFiddle demo.
Use prop() to set the readonly property of the text-box.
Create an array of all the values of the drop-down which, when selected, the number text-box should be disabled.
Check if the selected value is in the array in the change event handler
If the selected option value is present in the array, disable the number text-box, else enable it
Demo
$(document).ready(function() {
// Values when selected, the number box should be disabled
var values = ['option2', 'option3'];
// On selection change of the dropdown
$("#s_id").change(function() {
// values.indexOf($(this).val()) > -1
// Checks if the value selected is from the array
// Comparison returns true when the value is in array, false otherwise
$('input[name="number"]').prop('readonly', values.indexOf($(this).val()) > -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number:
<input type="text" name="number">
Try following code :-
$(this).attr("disabled", true);
I think drop down is always read only . what you can do is make it disabled
if you work with a form , the disabled fields does not submit , so use a hidden field to store disabled dropdown value
Please use this, You can also use it dynamically
Given below the HTML code
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" id="number" name="number">
Given below the JQuery code
$(document).ready(function () {
$("#s_id").change(function () {
var option_Array = ["option3","option4"]
var x = $(this).val();
$("#number").prop('readonly', false);
for(var i=0; i<option_Array.length; i++){
if (x == option_Array[i]){
$("#number").prop('readonly', true);
}
}
});
});

Change value of form input based on check box click

I have a form with validation, but im looking for a way to allow a check box to force a value for a form field so the validation will not see it as blank once the check box is clicked.
I currently have:
if (document.drop_list.Make.value == "")
{
message = message + "Make is missing\n";
valid = false;
}
I also have a check box, with this function:
// add event handler to checkbox
element.addEventListener('change', function() {
// inside here, this refers to the checkbox that just got changed
textbox = document.getElementById('textbox_1');
textbox.disabled = this.checked;
Can I add something to that function to force a value for:
<SELECT class="enteredMake" onchange=SelectModel(); name=Make id="textbox_2">
<OPTION selected value="">Vehicle Make</OPTION>
</SELECT>
This way, it wont be blank, it would be, say "Checked"
allowing the validation to pass?
So are you looking for something that will set the value of a select box once a checkbox has been ticked? For example:
selectbox = document.getElementById('myselectbox');
checkbox = document.getElementById('mycheckbox');
checkbox.addEventListener('change', function() {
selectbox.value = "1"
});
HTML:
<input type="checkbox" id="mycheckbox" />
<select id="myselectbox">
<option value="-1">Please select...</option>
<option value="1">1</option>
</select>
JSFiddle

getting an onclick event to a select option using js

i am having a very frustrating problem. I have this code
which filters out my results and inputs them into a select box
var syn = <?=json_encode($syn)?>;
function filterByCity() {
var e = document.getElementById("city_filter");
var city = e.options[e.selectedIndex].value;
var selectOptions = document.getElementById('syn_list');
selectOptions.options.length = 0;
for (i = 0; i < syn.length; i++) {
if (city == syn[i]['city'] || city == 'all') {
selectOptions.options[selectOptions.options.length] = new Option(syn[i]['name'], syn[i]['id'] + '" onclick="updateTxtContent(\'' + syn[i]['id'] + '\')');
}
}
}
as you might see i am adding a onclick listener to every select "option" which look great in the source code of the page itself but if i copy it into an edit i notice this
my problem is that the "updateTxtContent()" function is not called.
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;">
<option value="13" onclick="updateTxtContent('13')">option a</option>
<option value="14" onclick="updateTxtContent('14')">option b</option>
obviously there should be a better way to do this that i am not aware of.
maybe try an onchange event in your select tag.
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;" onchange='updateTxtContext(this.value);'>
I think you want to have your event handler on your select rather than on the option. See this fiddle for what I mean
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;" onchange="updateTxtContent();">
<option value="13">option a</option>
<option value="14">option b</option>
</select>
<script>
function updateTxtContent(){
alert($("#syn_list").val());
}
</script>
​
Or since it looks like you aren't using jQuery:
function updateTxtContent(){
var e = document.getElementById("syn_list");
var f = e.options[e.selectedIndex].value;
alert(f);
}
option elements can not have click events in most browsers.
And new option is setting the value and the text, not sure why you think you can set other attributes with it.
You want to use a change event on the select element.
As of 2016 it looks like click events are supported for selects and have the option clicked upon as target:
using jQuery
click_handler = function(e) {
alert('clicked on: ' + e.target.value);
}
$('#syn_list').click(click_handler);
Works at least in Firefox 44

Categories