I am trying to modify some JavaScript that I have to make it so that when a option is selected depending on the num value it will run a different action.
Here is what my current JavaScript looks like:
jQuery(".frequency_new_selector").on("change", function() {
jQuery('.frequency_new_label option:first-child').attr("disabled", "disabled");
jQuery(".frequency_num").val(jQuery(".frequency_new_selector").find("option[value='" + jQuery(".frequency_new_selector").val() + "']").data("num"));
jQuery(".frequency_type").val(jQuery(".frequency_new_selector").find("option[value='" + jQuery(".frequency_new_selector").val() + "']").data("type"));
jQuery(".frequency_type_text").attr("value", jQuery(".frequency_type option[value='" + jQuery(".frequency_type").val() + "']").text());
if (jQuery(".frequency_new_selector").val() !== null && $(".single-option-radio input:checked").length == $(".single-option-radio").length) {
jQuery("#AddToCart").removeAttr("disabled");
}
});
I would like to add a line in that looks like this:
if (jQuery(".frequency_new_selector").val() == 1 {
event.preventDefault();
$('.cd-popup').addClass('is-visible');
}
My HTML looks like this:
<div class="frequency_new_label" style="">
<select class="frequency_new_selector">
<option selected="selected" disabled="disabled">Please Select Shipping Interval</option>
<option data-type="2" data-num="1" value="1">Weekly</option>
<option data-type="3" data-num="1" value="2">Monthly</option>
</select>
</div>
Yours should work the way you have done it... However i would probably change it slightly as you are making an unnecessary jQuery call and they are quite expensive operations.
When your change callback gets called this will be assigned to the DOM element (dropdown).
$(".frequency_new_selector").on("change", function() {
if (this.value === '1') {
event.preventDefault();
$('.cd-popup').addClass('is-visible');
}
});
Related
I have a select tag with two options 'new' and 'edit'
when someone selects the 'new' option all the input tags in that form should be marked required and when someone selects 'edit' only a few should be marked required.
<select name="todo" id="todo" required>
<option value="">---</option>
<option value="new">Add</option>
<option value="edit">Edit</option>
</select>
Now I tried some functions but they don't seem to work
<script>
var todo = $('#todo option:selected').text();
if (todo == "new") {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
</script>
and
<script>
function req() {
var selectBox = document.getElementById('todo');
var userInput = selectBox.options[selectBox.selectedIndex].value;
if (userInput == 'new') {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
}
</script>
where
<select name="todo" id="todo" onchange="return req();" required></select>
just to be sure if it works I put a alert() method in the if condition, but that alert is never fired.
PS. one of the input tags is
<input type="text" id="Name" name="Name">
Thank you for your time in advance...
EDIT
As pointed out by #Maximillian Laumeister in second snippet there was a typo error (which I have corrected here). (sorry for that)
This should be ebough to get you going.
onchange detects whenever a different selection is made. Then based on what option is selected you perform the different instructions.
jQuery(document).ready(function(){
jQuery('#todo').on('change', function(event){
alert(this.value);
if(this.value === 'edit'){
}
else if(this.value === 'new'){
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select name="todo" id="todo" required>
<option value="">---</option>
<option value="new">Add</option>
<option value="edit">Edit</option>
</select>
In your script here you have a typo that throws a console error:
function req() {
var selectBox = document.getElementById('todo');
var userInput = selectBox.options[selectbox.selectedIndex].value;
if (userInput == 'new') {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
}
Where it says
selectBox.options[selectbox.selectedIndex].value
selectBox needs a capitalization like this:
selectBox.options[selectBox.selectedIndex].value
It seems to be working for me with that one change.
Also, since you asked, your first script isn't working because it needs to be bound to run when the select changes, just like with the first one. In addition, you need to use jQuery's val instead of text to get the value of an option tag. Here is a working version of your second script:
$("#todo").change(function () {
var todo = $('#todo option:selected').val();
if (todo == "new") {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
});
Try this:
$("select").change(function(){
if($(this).val() === "new")
$("#Name").attr("required","required");
});
You used the option text which is "Add" but in your if statement you compared it to the string "new". That's the reason your code didnt work as expected.
I have datalist like below -
<input id="name" list="allNames" />
<datalist id="allNames">
<option value="Adnan1"/>
<option value="Faizan2"/>
</datalist>
What I want is, when an item is typed in completely(for example say in input box when user completely type "Adnan1") or selected from list, then I want an event. I tried couple of approaches but both doesn't help me so far. Approaches are -
$("#name").change(function(){
console.log("change");
}
problem with this is, the event only gets triggered when input gets out of focus I.e. when I click somewhere in the screen.
I also tried
$("#name").bind('change', function () {
console.log('changed');
});
but the callback gets triggered each time when I type in. I actually need to make an AJAX call when item is completely selected. Either via type-in or by selecting from dropdown.
First approach is bad for user perspective because he has to make extra click and second has disadvantage as for every letter an event will be triggered.
All I want is an event when either user made a selection or typed complete sentence. is there a way to achieve this? any event that I missing and that can solve my problem.
On modern browsers, you can use input event, e.g:
$("#name").on('input', function () {
var val = this.value;
if($('#allNames option').filter(function(){
return this.value.toUpperCase() === val.toUpperCase();
}).length) {
//send ajax request
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="name" list="allNames" />
<datalist id="allNames">
<option value="Adnan1" />
<option value="Faizan2" />
</datalist>
PS: as input event has better support than datalist element, there is indeed no reason to not use it if you are already using datalist element.
You can use input event for achieving such functionality, as below :
$(document).ready(function() {
$('#name').on('input', function() {
var userText = $(this).val();
$("#allNames").find("option").each(function() {
if ($(this).val() == userText) {
alert("Make Ajax call here.");
}
})
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" list="allNames" />
<datalist id="allNames">
<option value="Adnan1" />
<option value="Faizan2" />
</datalist>
Simple solution
document.getElementById('name').addEventListener('input', function () {
console.log('changed');
});
Hacky as a sin, but works for me. (Note that if you are typing 'Rum-Cola' it doesn't stop on the 'Rum' option)
const opts = $("option").map(function(){return this.value;}).get();
$("#favourite-drink").on("keydown", function(e){
if(e.key){ // in case of mouse event e.key is 'undefined'
if (e.key === "Enter") { // looks like user wants to confirm the choice
if(opts.indexOf(this.value) >= 0){
this.blur();
console.log("Selected: " + this.value);
}
}
else {
this.setAttribute("data-keyboardinput", "true"); // remember that it's keyboard event
setTimeout(function(){ //and keep it in memory for 100ms
this.removeAttribute("data-keyboardinput")
}.bind(this), 100);
}
}
});
$("#favourite-drink").on("input", function(){
if(!this.dataset.keyboardinput && opts.indexOf(this.value) >= 0){ // if it's not a key press followed event
console.log("Selected: " + this.value);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Choose a drink:</p>
<input id="favourite-drink" list="drinks">
<datalist id="drinks">
<option value="Rum"></option>
<option value="Rum-Cola"></option>
<option value="Vodka"></option>
</datalist>
Check if this works for you :
var dataList=[];
$("#allNames").find("option").each(function(){dataList.push($(this).val())})
console.log(dataList);
$("#name").on("keyup focus blur change",function(){
if(dataList.indexOf($(this).val())!=-1)
console.log("change");
})
I pushed datalist options into array , and on change event keyup , blur or focus , i check if input value exists in my datalist array.
In addition to what was said above, we can also check the inputType of the input which must correspond to "insertReplacementText"
function textThatComesFromADatalist (event){
const inputType = event.inputType;
const isReplacingText = (typeof inputType === "undefined")
|| (inputType === "insertReplacementText");
return isReplacingText;
}
function onInput(event) {
if(textThatComesFromADatalist(event)){
alert('selected: '+event.target.value);
}
}
<input oninput="onInput(event)" list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
Simple solution is that check the input text value exist in datalist or not, and if it does, run an ajax request.
$("#input_form").on('input', function(event){
if ($("#input_datalist option[value='" + $('#input_form').val() + "']").val() != undefined) {
//send ajax request
}
});
I have the following code that does not seem to work:
$('.chosen-select').on('change', function() {
if ('.chosen-select'.value == '1') {
$("#tips").html("the color that you want to add.");
} else if ('.chosen-select'.value == '2') {
$("#tips").html("the text that you want to add.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="tips"></div>
<select class="chosen-select" style="width:290px;" name="option">
<option value="1">change background colour</option>
<option value="2">insert text</option>
<option value="3">insert arrow</option>
</select>
My web browser console is not giving me any error. The code is suppose to change the html of the div based on changing the select option value.
This '.chosen-select'.value won't work as it's neither a valid jQuery expression nor JavaScript. Instead use $('.chosen-select').val(), this.value or $(this).val().
jsFiddle example
Use if($(this).val() == '1') { not as if('.chosen-select'.value == '1')
$(function() {
$('.chosen-select').on('change', function() {
if($(this).val() == '1') {$("#tips").html( "the color that you want to add.");}
else if($(this).val() == '2') {$("#tips").html( "the text that you want to add.");}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="tips"></div>
<select class="chosen-select" style="width:290px;" name="option">
<option value="1">change background colour</option>
<option value="2">insert text</option>
<option value="3">insert arrow</option>
</select>
The below expression doesn't yield the results you want:
'.chosen-select'.value
It attempts to access the value property of a String object, which is undefined, because strings don't have such properties.
Within the change event handler function, you can make good use of the fact that this references the <select> element:
var selectedValue = this.value; // get value from select element
Alternatively, use jQuery's .val() function to get the value:
var selectedValue = $(this).val();
Briefly Explaining my program :
I Have 3 select boxes
If the value selected by the user in the 1st box is 2 & Value selected by the user in second box is 3 (option values) then the third select box should display an array.
This code doesn't work but shows an idea:
if ($('#firstbox').click(function() { ($(this).val() == '2'); } &&
$('#secondbox').click(function() { ($(this).val() == '3'); }) {
// Array Display here (not included the coding here, because there is no issue with this coding.. seems working fine)
}
I need help for the code included in if statment and && operation for checking the expression.
var select1 = $('#firstbox');
var select2 = $('#secondbox');
$([select1, select2]).change(function () {
if ( select1.val() == 2 && select2.val() == 3 ) {
// run your code here...
}
});
You need to either bind the click event to the third select box or bind to the change event of the first two boxes and callback a common function which updates the third one.
$("#firstbox, #secondbox").change(UpdateThird);
function UpdateThird() {
var a = $("#firstbox").val();
var b = $("#secondbox").val();
if (a == 2 && b == 3) {
// ...
}
}
assuming
<select id="firstbox">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="secondbox">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
script:
$('#secondbox, #firstbox').on('change',function(){
if($('#firstbox').val() == 2 && $('#secondbox').val() == 3)
alert('array display code here...');
})
I am appending some HTML elements to the page dynamically. There can be multiple items added and can be added a different times...so it is hard to use a "bind".
I decided to use an inline function---but this does not work on Firefox...works on all other browsers. Notice the onClick for the options. Also, I have tried onblur, onchange, and on select. None of these work with Firefox.
My goal is to have these functions run when the option is selected. I guess I am just missing something.
$("#billTasks").find('tr')
.append('<td><fieldset><select>
<option class="fixedRate" onClick="fixedOption(this)" id="billFixedSelect" value="1">Fixed Rate</option>
<option class="hourly" onClick="hourlyOption(this)" id="billHourlySelect" value="2"></option>
</select>
<input type="text" placeholder="Rate" class="fieldWidth100 rate currency" style="margin-right:10px;"/>
<select class="schedule">
<?php while($row = $db->sql_fetchrow($result)){
echo "<option value=\'{$row['schedule']}\'>{$row['schedule']}</option>\\n";}?>
</select></fieldset></td>');
This is the code in question (in the append string)
<select>
<option class="fixedRate" onClick="fixedOption(this)" id="billFixedSelect" value="1">Fixed Rate</option>
<option class="hourly" onClick="hourlyOption(this)" id="billHourlySelect" value="2"></option></select>
Why Inline You try some thing like this.
$("#billTasks").find('select').live("change", function() {
var SelectedValue = $(this).val();
if (SelectedValue == '1') {
//your task
}
if (SelectedValue == '2') {
//Your Task
}
});
You can use delegate event handler for that:
$('#billTasks ').on('change', 'select', function() {
// your code
hourlyOption(this); // here this points to select itself
});
Read here
I would recommend using a class for this. What you could do is something like this:
function Option(html, events) {
var o = $(html);
for(var k in events) {
o.bind(k, events[k]);
}
return o;
}
Use this something like this:
var o = new Option('<option>blah</option>', { click: function() { } ... });
and o is just a new jquery object. So you can use it anyway.