Remove "selected" from an option of a dropdown - javascript

I am working on a form. One of my colleagues have used the are_you_sure.js which confirms to leave before saving a form.
Now the problem is if I have a dropdown say like this
<script type="text/javascript">
function get_cpc(cst_type)
{
if(cst_type==0 || cst_type==1)
{
$("#camp_cpc").show();
$("#camp_cpc").val("'.(!empty( $html['camp_cpc'] )?(double)$html['camp_cpc']:'').'");
}
else
{
$("#camp_cpc").hide();
$("#camp_cpc").val("0");
}
}
</script>
<select name="cost_type" id="cost_type" onchange="get_cpc(this.value);" class="ultra-select">
<option value="0">CPC</option>
<option value="1" selected="selected">CPA</option>
<option value="2">Do Not Track</option>
</select>
When I am switching from non-selected options to selected option, then the change of state takes too much time
This means if I am selecting CPC/Do Not Track from CPA, then the dropdown works fast. But if I am selecting CPA from CPC/Do Not Track, then the state change takes almost 4 seconds..
That's due to the jquery.are-you-sure.js. So, I need to remove the select from the dropdown. How can I achieve this?
I put this code, $("select option").prop("selected", false);
but it doesn't even let me select any other option.

I'm not sure what you mean exacly, but can you share the are_you_sure.js file?¿
Also I have change your code maybe it helps and it´s a better way to do it. because it´s not a good practice use onchange(), so remove onchange from your html and do this, link: http://jsfiddle.net/hg5nz1w6/1/
js:
$(document).ready(function(){
$('#cost_type').on('change', function(){
var cst_type = $(this).val();
if(cst_type==0 || cst_type==1)
{
$("#camp_cpc").val("'.(!empty( $html['camp_cpc'] )?(double)$html['camp_cpc']:'').'");
$("#camp_cpc").show();
}
else
{
$("#camp_cpc").hide();
$("#camp_cpc").val("0");
}
});
});
html:
<select name="cost_type" id="cost_type" class="ultra-select">
<option value="0">CPC</option>
<option value="1" selected="selected">CPA</option>
<option value="2">Do Not Track</option>
</select>
Below you can see some examples to remove the selected:
document.getElementById('myselect').selectedIndex = -1;
you can deselect all the options:
$("select").val([]);
or
$("select option").prop("selected", false);
Hope it´s helps!

Related

How can I fire an event in an option tag?

I looked for a solution for this, but couldn't find it.
I have a simple select like this:
<select id="sltFiltroPedidos">
<option value="todos">Todos</option>
<option value="hoje">de hoje</option>
<option value="semana">da semana</option>
<option value="periodo">Período</option>
<option value="pedido">Número do pedido</option>
</select>
Always the user clicks on an option, a javascript event must be fired.
The onChange event in the select doesn't work for me, because the user can choose the same option, and the event must be fired as well.
I tried the onClick event on options. It works on IE and FF, but doesn't work on Chrome.
Any ideas how can I do it?
I wrote a code but it is not working on IE, just give it a try: http://jsfiddle.net/shahe_masoyan/scuhb/1/
<select id="sltFiltroPedidos">
<option value="todos">Todos</option>
<option value="hoje">de hoje</option>
<option value="semana">da semana</option>
<option value="periodo">Período</option>
<option value="pedido">Número do pedido</option>
</select>
var isOpen = false;
$('#sltFiltroPedidos').on('mouseup', function () {
if (isOpen){
alert(this.value);
}
isOpen = !isOpen;
});
As per your question you can do following :-
<select id="sel" onblur="showme()">
<option value="todos" >Todos</option>
<option value="hoje" >de hoje</option>
<option value="semana" >da semana</option>
<option value="periodo" >Período</option>
<option value="pedido" >Número do pedido</option>
</select>
But i don't know this right option or not. But this will work as you told.
function showme()
{
alert(document.getElementById('sel').value);
}
You can try onclick like,
var prevValue=$('select').val();
$('select').on('click',function(){
if(prevValue==this.value) // code for same values
// your code to run
});
I had the same issue. In my task, I needed to get the value of the selected option. This helped me:
let selectedOption = "";
<select>.addEventListener("change", event => {
selectedOption = event.target.value
});
The select variable is, obviously, the tag .
It might look strange, but select takes the value of the chosen option, that's why the code works.
Use:
$('#sltFiltroPedidos').on('change', function() {
alert( this.value );// or this.val()
});
Hope this will work for you

div hide/show if statements multiple drop boxes

Firstly, this is my first ever time using jQuery, so my code is not going to be the best. I'm adding a filter to my works website based off 3 drop boxes: fuel type, drive-type, and vehicle type. I want that when someone selects petrol it shows all the petrol cars, which I have managed to achieve, but now I'm a bit stuck. I now want it to show based on all 3 boxes, so if someone selects petrol, and then auto and then cars, it will show only petrol automatic cars. I can't seem to make the 3 boxes work together. so please help.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// fuels
$("#fuel").change(function() {
if ($("#fuel option[value='petrol']").attr('selected')) {
$('div[class*=petrol]').css('display','block');
}
if ($("#fuel option[value='diesel']").attr('selected')) {
$('div[class*=diesel]').css('display','block');
}
// end
//drivetype
});
$("#drive").change(function() {
if ($("#drive option[value='man']").attr('selected')) {
$('div[class*=manual]').css('display','block');
}
if ($("#drive option[value='auto']").attr('selected')) {
$('div[class*=auto]').css('display','block');
}
//end
});
// vech type
$("#type").change(function() {
if ($("#type option[value='car']").attr('selected')) {
$('div[class*=car]').css('display','block');
}
if ($("#type option[value='4']").attr('selected')) {
$('div[class*=4]').css('display','block');
}
if ($("#type option[value='7']").attr('selected')) {
$('div[class*=7]').css('display','block');
}
if ($("#type option[value='van']").attr('selected')) {
$('div[class*=van]').css('display','block');
}
// end
});
});
<select id="fuel">
<option value="none">fuel</option>
<option value="petrol">petrol</option>
<option value="diesel">diesel</option>
</select>
<select id="drive">
<option value="none">drive</option>
<option value="man">manual</option>
<option value="auto">auto</option>
</select>
<select id="type">
<option value="none">type</option>
<option value="car">car</option>
<option value="4">4x4</option>
<option value="7">people carrier</option>
<option value="van">van</option>
</select>
Basically at the time when you want to show the cars, you want to check all 3 select boxes for their values so you know which cars to show
In this case when showing cars for "auto" you need to check petrol as well as auto. when showing cars for "cars" you need to check all 3.
edit:
$("#type").change(function() {
// check previous select box value, check this box value
// output the correct cars
});
for the last one you simply check both of the previous boxes and this box and output the correct cars
Try to do something like:
$("#fuel").change(function() {
var value = $(this).val();
$(".elements_to_hide").hide(); //check if needed
$("." + value).show();
});
Please dont take it personally, but Ill give some suggestions about your code:
Try to avoid such complex constractions like: $('div[class*=diesel]').It will affect the performance.
JQuery contains build-in functions for show/hide DOM elements — .show(), .hide()
To get selected option of "select" use .val();
Hope answer will helpful for you. Best regards!

Select-box control with jquery

I am using a selectbox:
<select name="priority" id="priority">
<option value="4">Low</option>
<option value="3" selected="selected">Normal</option>
<option value="2">High</option>
<option value="1">Emergency</option>
</select>
When user select "Emergency", then a confirmation box opens and if user confirm, then "Emergency" is selected. Otherwise "Normal" should be selected. For This, I am using jquery:
$(document).ready(function() {
$('#priority').change(function(){
if($(this).val()=='1'){
if(confirm("Are you sure this is emergency?")){
return true;
}
else{
//here some code is needed to select "Normal".
}
}
});
});
Now, How can I do that?
Since you're just returning in the confirmation case, you can shorten your logic down to this:
$(function() {
$('#priority').change(function(){
if($(this).val()=='1' && !confirm("Are you sure this is emergency?")){
$(this).val('3');
}
});
});​
You can give it a try here.
else{
$(this).find("option[value=3]").attr("selected","selected");
//and trigger change after that if you need it
$(this).change();
}
The following code snippet should do what you are after - it selects the priority select element by ID and then sets the selected value to 3.
else
{
$('#priority').val(3);
}

Yes/No confirmation message

I'm trying to get an alert message with Yes/No option, where clicking on 'Yes' reloads a another drop-down option, and 'No' would revert back to the previous selection. Here is what I'm trying to say (obviously doesn't work):
<select size="1" name="m" id="m">
<option selected value="1">apple</option>
<option value="2">ball</option>
<option value="3">cat</option>
<option value="4">dog</option>
<option value="5">egg</option>
</select>
$('#m').change(function() {
var answer = confirm("this will change your selection.");
if (answer) { // ie, if i click 'OK'
location.reload(); // reload the <select> option below to "selected"
} else {
break; // revert back to the previous selection
}
});
<select size="1" name="a" id="a">
<option selected value="1">aaa</option>
<option value="2">bbb</option>
<option value="3">ccc</option>
</select>
Many thanks in advance. Feel free to click, and edit.
I'm not too sure what you are trying to accomplish... is it this?
var _selected = $('#m').val();
$('#m').change(function() {
var answer = confirm("this will change your selection.");
if (answer) { // ie, if i click 'OK'
_selected = $(this).val();
$('#a').val(_selected);
} else {
$(this).val(_selected);
}
});​
JavaScript's confirm() only displays OK and Cancel, not Yes or No.
Could you return false instead of break, because you are in a function?
Also, returning false does not cancel the change event. What you will need to do is store the previous selectedIndex, and if you have the confirm() return false, then set the selectedIndex back to the previous one.
Also, I hope you are wrapping that jQuery inside script elements and inside a $(document).ready().
Try removing the
break;
I tried to run the code and Firebug halts the code when it gets to that part
Best regards,

Javascript - onchange within <option>

I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information.
With the help of a few online tutorials, I've managed to get the Javascript to display a hidden div just fine. My problem is I can't seem to localise the event to the Option tag, only the Select tag which is no use really.
At the moment the code looks like (code simplified to aid clarity!):
<select id="transfer_reason" name="transfer_reason onChange="javascript:showDiv('otherdetail');">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
What I would like is if they choose "Other Reason" it then displays the div. Not sure how I achieve this if onChange can't be used with the Option tag!
Any assistance much appreciated :)
Note: Complete beginner when it comes to Javascript, I apologise if this is stupidly simple to achieve!
Setup the onchange event handler for the select box to look at the currently selected index. If the selected index is that of the 'Other Reason' option, then display the message; otherwise, hide the division.
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 2) {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</body>
</html>
Personally, I'd take it a step further and move the JavaScript into an external file and just include it in the header of the page; however, for all intents and purposes, this should help answer your question.
After reading Tom's great response, I realised that if I ever added other options to my form it would break. In my example this is quite likely, because the options can be added/deleted using a php admin panel.
I did a little reading and altered it ever so slightly so that rather than using selectedIndex it uses value instead.
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.value === "Other") {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
Hope this helps someone else in the future!
Tom's answer is elegant, and neatly puts the JS away from the HTML markup. As mentioned, it could be even moved to an external file. However it adds quite much "nonsense" to the code, like multiple anonymous function assignments etc.
If you want quick solution, you can put it all in the onchange() inside the select tag as well. Pick the one you see more fit.
<select id="transfer_reason" name="transfer_reason" onchange="document.getElementById('otherdetail').style.display = (this.selectedIndex === 2) ? 'block' : 'none';">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>

Categories