preventDefault() not working on a particular option select - javascript

I have this <select> list that takes different options and reroutes based on the one clicked. The html code is:
<select id="pageSelect" name="Choose Page" onchange="location = this.value">
<option value='' disabled selected hidden>Choose Page</option>
<option value='/page-1'>Page 1</option>
<option value='/page-2'>Page 2</option>
<option value="allPages" >Custom Page</option>
</select>
The rerouting of the first 2 pages work as expected. However, the third option is going to be handled using a custom Javascript function instead of being handled by the onchange function declared at the <select> element.
The custom function for the last <option> is:
$('#pageSelect').change(function(event) {
event.preventDefault()
var pagesvalueselect = $(this).val();
if(pagesvalueselect=="allPages"){
$('#siteSaleModal').modal("show"); //Open Modal
}
});
The function works and when a user clicks on the last option, it triggers the modal to pop up but it still redirects the user to another page based on value="allPages" even though I am using the preventDefault() function.

The preventDefault() call only stops the current change event handler. The one you've assigned via the onchange attribute will still run regardless as it's entirely separate.
To fix this, and improve your code, remove the onchange attribute (as they are outdated and now considered bad practice) and combine them in to one unobtrusive event handler.
$('#pageSelect').change(function(event) {
event.preventDefault()
var pagesvalueselect = $(this).val();
if (pagesvalueselect == "allPages") {
console.log('open modal...');
//$('#siteSaleModal').modal("show"); //Open Modal
} else {
console.log('redirecting to ' + pagesvalueselect + '...');
//window.location.assign(pagesvalueselect);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pageSelect" name="Choose Page">
<option value="" disabled="true" selected="true" hidden>Choose Page</option>
<option value="/page-1">Page 1</option>
<option value="/page-2">Page 2</option>
<option value="allPages">Custom Page</option>
</select>

Your code code works fine without event.preventDefault() and onchange attribute.
<select id="pageSelect" name="Choose Page">
<option value='' disabled selected hidden>Choose Page</option>
<option value='/page-1'>Page 1</option>
<option value='/page-2'>Page 2</option>
<option value="allPages" >Custom Page</option>
</select>
$('#pageSelect').change(function(event) {
var pagesvalueselect = $(this).val();
if(pagesvalueselect=="allPages"){
$('#siteSaleModal').modal("show"); //Open Modal
} else {
location = pagesvalueselect;
}
});
Codepen

Related

How can i put an option value in a input text after clicking a button?

I'm not familiar with javascript and jQuery and I'm asking you.
I would like the code of a product to be selected, once I have selected it from the select dropdown, I click the button and it should add the value in an input box text, that I have created, so that I can also accumulate more codes of more products.
Keep in mind that once the button is clicked, the same value is no longer added indefinitely but that it is possible to choose another code and add it next to the one already present in the input text.
I don't know if it is more practical to use the <input type = "submit"> tag instead of the button tag to send or in this case transfer the selected text from the select to a text form.
You would save my life if you could please complete this action for me with javascript or jQuery :)
<select class="select" id="select-code">
<option value="">Select a code</option>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input name="my-quote" type="text" placeholder="code1,code2...">
First of all, it seems that you are complete beginner. so you should learn DOM api to learn how to manipulate the window.
Anyway here is the code to do so which you want;
document.getElementById('code-btn').onclick = () => {
let e = document.getElementById('select-code');
document.getElementById('input').value = e.options[e.selectedIndex].text;
}
<select class="select" id="select-code">
<option value="">Select a code</option>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id='input' name="my-quote" type="text" placeholder="code1,code2...">
document.getElementById('code-btn') gets the element with id 'code-btn'. As that is a button, we can use onclick property which will will take a function and that function will be called when it is clicked.
Inside that function, i am simply getting the input field and setting its value to the text of the selected option from dropdown.
I think the code here is self-documented.
This isn't a direct answer to your question, but an alternative solution. If possible for your situation, I would consider using <select multiple>: the select tag with the "multiple" attribute. It's a native HTML feature that allows the user to select multiple options from the list. I don't know how you're submitting the form data, but if using a <form> tag then the form's data will include which values have been selected.
Tutorial about select multiple
<label for="select-code">Select a code</label>
<select class="select" id="select-code" multiple>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id='input' name="my-quote" type="text" placeholder="code1,code2...">
This is actually very simple and might be used as beginers excercise, so I'm gonna give you a brief walkthrough of how I would solve it:
register button onClick event
read selected value
add it to the placeholder attribute
so something like this (not tested at all)
//button click event
$("#code-btn").click(function (event) {
//in element #select-code
var textToAdd = $('#select-code')
//find element with pseudo selector :selected
.find(":selected")
//get its inner text
.text();
//check if input already contains the text here, if not
if (!$("input").attr("placeholder").includes(textToAdd)) {
//into input element
$("input")
//into attribute placehoder
.attr("placeholder",
//insert original text //insert colon //insert new text
$("input").attr("placeholder") + ", " + textToAdd)
}
});
function myFunction() {
var newText = document.getElementById('select-code').value
var input = document.getElementById('my-quote')
if (input.value == '') input.value = newText
else input.value = input.value + ', ' + newText
}
<select class="select" id="select-code" onchange='myFunction()'>
<option value="">Select a code</option>
<option value="Code 1">Code 1</option>
<option value="Code 2">Code 2</option>
<option value="Code 3">Code 3</option>
<option value="Code 4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id="my-quote" type="text" placeholder="code1,code2...">

Can't get value of dropdown list item using Jqoery

I have a drop down list, which is within a pop modal. The drop-down list looks like this:
<select name="EventTypeId" class="form-control formTextBox" id="ddlEventType">
<option value="">Please Select</option>
<option value="1">Assessment</option>
<option value="2">Single Session</option>
<option value="3">Group Session</option>
</select>
And my jquery looks like this:
$("body").on("change", "#ddlEventType", function (e) {
var test = $('#ddlEventType').val();
});
It hits the onchange function no problem, but whenever I select an option on the ddl, the test variable is always "", never gets the value. Can anyone help me with what's going wrong here? Is it because the ddl is inside a modal popup? I actually have a ddl in a different modal popup, with the exact same code and it works completely as it should. There's no conflicting ids on the age either. Can't figure out why I'm not getting the value.
UPDATE
I gave the ddl a class name of ddlEventType, and changed the jquery to
$("body").on("change", "#ddlEventType", function (e) {
var test = $('.ddlEventType').val();
});
and for some reason this worked. Don't get why, but it works and that's all I need. Thanks for your help everyone.
Try this:
$(document).on('change','#ddlEventType',function(){
console.log($(this).val());
});
Are you doing any change to the body. And for preventDefault it should be e.preventDefault();
You can follow the below methods for obtaining the selected value from the select tag using the onchange() attribute.
First method i have called the onchange() directly to the script function.
Second Method i have given directly a function to the select tag and then called the function in the script file.
First Method:
$(document).ready(function(){
$("#ddlEventType").change(function(){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="EventTypeId" class="form-control formTextBox" id="ddlEventType">
<option value="">Please Select</option>
<option value="1">Assessment</option>
<option value="2">Single Session</option>
<option value="3">Group Session</option>
</select>
Second Method:
function get_value(a)
{
alert(a);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="EventTypeId" class="form-control formTextBox" id="ddlEventType" onchange="get_value(this.value)">
<option value="">Please Select</option>
<option value="1">Assessment</option>
<option value="2">Single Session</option>
<option value="3">Group Session</option>
</select>

How to change "size" of select when click on select?

sorry for my bad english, i have a problem with select :
<form name="reg" style="width:700px;" action="#" method="post">
<p align="center">
<select onChange="reg(this.options[this.selectedIndex].value)" size="1">
<option selected value="250">Select the Reg</option>
<option value="0">Reg 1</option>
<option value="1">Reg 2</option>
<option value="2">Reg 3</option>
<option value="3">Reg 4</option>
<option value="4">Reg 5</option>
<option value="5">Reg 6</option>
<option value="6">Reg 7</option>
<option value="7">Reg 8</option>
<option value="8">Reg 9</option>
<option value="9">Reg 10</option>
</select>
</p>
</form>
I would like that when i click on select, the size of select changes in size="5", because when the document load the size is size="1" (and this is good) but if i click on select, it shows all ten options, and this is the problem...
While, if i click on select, the size changes, is most beautiful.
EDIT
In future the form could have more 250 options, so is important that when the document load size is 1, and when i click the size is 5 ....
the size must be "5" only when the select show options, and when an option is selected the size must be 1.
The problem is that i don't know how made it, maybe with jquery? or only with css?
Can you help me?
Thanks!
Here is a working solution for your problem:
add focus event handler to the select list with id='selRegs'
set the size attribute to 6 (5 will show 4 options + the "Select the Reg" option)
after option is changed the size will be reset to 1
remove focus from select
https://jsfiddle.net/juaxo8zm/8/
$(document).ready(function () {
var initPos = $("#yourDiv").position();
console.log("init: ");
console.log(initPos);
$('#selRegs').focus(function () {
$('#selRegs').attr("size", "6");
$("#yourDiv").css({
position: "absolute",
top: initPos.top,
left: initPos.left
});
});
$('#selRegs').change(function () {
console.log("selected");
$('#selRegs').attr("size", "1");
$("#selRegs").blur();
$("#yourDiv").css({
position: "static"
});
});
});
I use jQuery for this:
.change()
.focus()
.attr(param1, param2)
.blur()
.position()
Try this:
<select size="1"
onfocus='this.size=5;'
onblur='this.size=1;'
onchange='this.size=1; this.blur();'
>
Use the HTML onclick="myFunction()" event tag from the HTML select tag, or use jQuery click() handler if you want to declare the event handler at the javascript level (I mean if you want add the additional event from javascript).
I mean you have a choice - add the extra event dispatch code in the HTML tag source code or add it from the javascript/jQuery level.
The problem is that onChange() event dispatch doesn't get called until too late for your need (it gets called after a user selects a value).
You need to get notified the moment the button for the drop-down menu is clicked so you can change the selected value (default) value.
In your click function handler change the selectedIndex property and set it to the the index of the line that contains "5"
You should use click event on select
$('select').on('click',function(){
$(this).attr('size',5)
});
Just use javascript :
<select id='sel' onfocus='changesize();' onchange='changesize2();' size='1'>
<option selected value="250">Select the Reg</option>
<option value="0">Reg 1</option>
<option value="1">Reg 2</option>
<option value="2">Reg 3</option>
<option value="3">Reg 4</option>
<option value="4">Reg 5</option>
<option value="5">Reg 6</option>
<option value="6">Reg 7</option>
<option value="7">Reg 8</option>
<option value="8">Reg 9</option>
<option value="9">Reg 10</option>
</select>
<script>
function changesize(){
document.getElementById('sel').size = '5';
}
function changesize2(){
document.getElementById('sel').size = '1';
document.getElementById('sel').blur();
}
</script>
Demo : http://codepen.io/anon/pen/zxbRZb

Trouble using JavaScript dropdown more than once on the same page

I'm using this code for a drop down function in a table, and it's working great. However, when I try to use it more than once on the same page, One is corrupting the information of the other. I've tried changing the id settings but it didn't work. What do I need to do to so I can use this multiple time on a singe page. I'm using Wordpress and placing the script in the header.
<script language="JavaScript" type="text/javascript">
<!--
function openPop(){
var Sel_Ind = document.getElementById('myURLs').selectedIndex;
var popUrl = document.getElementById('myURLs').options[Sel_Ind].value;
winpops=window.open(popUrl,"","width=400,height=338,resizable,")
}
//-->
</script>
</head>
<body>
<select id="myURLs" onChange="javascript:openPop();">
<option value="">Select a page...</option>
<option value="http://news.bbc.co.uk">News</option>
<option value="http://www.the-company.com">Music</option>
<option value="http://www.b3ta.com">Laughs</option>
<option value="http://www.google.com">Search</option>
<option value="http://www.sitepoint.com/forums">Help</option>
</select>
I think that's because you have hardcoded ids inside the onChange handler. Instead, what you can do is to pass the select element of which the onChange event fires into the handler function and use that to further processing.
<select id="myURLs1" onChange="openPop(this)">
<option value="">Select a page...</option>
<option value="http://news.bbc.co.uk">News</option>
<option value="http://www.the-company.com">Music</option>
<option value="http://www.b3ta.com">Laughs</option>
<option value="http://www.google.com">Search</option>
<option value="http://www.sitepoint.com/forums">Help</option>
</select>
<select id="myURLs2" onChange="openPop(this)">
<option value="">Select a page...</option>
<option value="http://news.bbc.co.uk">News</option>
<option value="http://www.the-company.com">Music</option>
<option value="http://www.b3ta.com">Laughs</option>
<option value="http://www.google.com">Search</option>
<option value="http://www.sitepoint.com/forums">Help</option>
</select>
Then in the handler function accept the select box into a parameter.
function openPop(sel){
var popUrl = sel.options[sel.selectedIndex].value;
winpops=window.open(popUrl,"","width=400,height=338,resizable,")
};
This way, you can have as many as select boxes you want and handler will behave correctly.
Check this fiddle for this implementation.
http://jsfiddle.net/BuddhiP/awc6o9ju/

Enable popup on select and url redirect on select control?

I want menu to be in select control, like this
<form id="go">
<select name="URL" onchange="window.location.href=this.form.URL.options[this.form.URL.selectedIndex].value">
<option value="">Select option</option>
<option onclick="openChangePassword()">Change password</option>
<option value="www.editpersonaldata.com">Edit personal data</option>
<option value="www.dashboard.com">Dashboard</option>
</select>
</form>
This is changing url not a problem, but i have problem with some option because values are calling function, onclick="openChangePassword() and it is not working this way, any solution.
On some option i need url redirect on other i need function call?
As A. Wolff points out in his comment, you should add an event listener to the <select> element instead. Like this:
<form id="go">
<select name="URL">
<option value="">Select option</option>
<option value="openChangePassword">Change password</option>
<option value="www.editpersonaldata.com">Edit personal data</option>
<option value="www.dashboard.com">Dashboard</option>
</select>
</form>
<script>
document.querySelector('select[name="URL"]').addEventListener('change', function(e){
var selection = this.options[this.selectedIndex].value;
if(selection == 'openChangePassword'){
openChangePassword();
} else {
window.location.href = selection;
}
});
</script>
Notice that I only use the value attribute of <option> and then decide what to do in the listener callback function.

Categories

Resources