Get selected option ID with Javascript - javascript

I have a tabs with select option in each tab and I want it to be submitted in a specific URL assigned to them when I hit submit button. I'm doing this in javascipt. I'm really a newbie in javascript that's why I need your generous help.
I divided my select option according to their category using tabs, so my code is like this:
HTML
<ul class="ut-nav-tabs clearfix">
<li class="active">Corporate Services
</li>
<li class="">
Digital Marketing
</li>
</ul>
<div id="t1Tab" class="tab-pane clearfix active">
<form method="post" action="/trendstatic15/#wpcf7-f3409-o1">
<select id="id_corporateservices">
<option value="Can a foreign investors open his own company in the Philippines?">Can a foreign investors open his own company in the Philippines?</option>
<option value="What are the business regulations currently used in the Philippines?">What are the business regulations currently used in the Philippines?</option>
</select>
</div>
<input class="wpcf7-form-control wpcf7-submit" type="submit" value="Submit">
</form>
</div>
<div id="t2Tab" class="">
<form method="post" action="/trendstatic15/#wpcf7-f3409-o1">
<select id="id_digitalservices">
<option value="Should I add online video to my web sites?">Should I add online video to my web sites?</option>
<option value="What works best in Internet marketing?">What works best in Internet marketing?">What works best in Internet marketing?">What works best in Internet marketing?</option>
</select>
</div>
<input class="wpcf7-form-control wpcf7-submit" type="submit" value="Submit">
</form>
</div>
JAVASCRIPT
<script type="text/javascript">
function redirect() {
var filename_corporate = document.getElementById('id_corporateservices').value;
var filename_digital = document.getElementById('id_digitalservices').value;
var url ='';
if (filename_digital == 'What works best in Internet marketing?')
{
url= 'http://localhost/testsite/digital-page';
}
else if(filename_corporate == 'Can a foreign investors open his own company in the Philippines?')
{
url= 'http://localhost/testsite/corporate-page';
}
else
{
url= 'http://anyurlpage.com';
}
window.location = url;
}
</script>
Why is that when I selected any in the option and then submitted it always direct to the first url condition http://localhost/testsite/digital-page?

Because you are always referring to the one element with id "id_digitalservices" that never changes? It does not matter if you change tabs visibility it still remains in DOM.
You can get the actually changed option value by using the following code:
<script type="text/javascript">
function selectmenuOnchange(selectMenuId) {
//Get the selectmenu element by Id
var selectmenuID = document.getElementById(selectMenuId);
//Get selected options value
var optionValue = selectmenuID.options[selectmenuID.selectedIndex].value;
//this should return the selectmenu's id
alert(this.id);
redirect(optionValue);
}
function redirect(optionValue) {
var url ='';
if (optionValue === 'What works best in Internet marketing?')
{
url= 'http://localhost/testsite/digital-page';
}
else if(optionValue === 'Can a foreign investors open his own company in the Philippines?')
{
url= 'http://localhost/testsite/corporate-page';
}
else
{
url= 'http://anyurlpage.com';
}
window.location = url;
}
</script>
You need to edit both of your selectmenus to include my onchange function like this:
HTML
<select onchange="selectmenuOnchange(this.id);">

Related

How to direct user to an specific page depending on selection they made after form submission?

I have created a list with 6 options and users can only select one. I want that whenever a user selects an option from the list after they submit the form it directs them to a specific page depending on which selection.
Eg. I have 3 options
Facebook
Youtube
Twitter
If the user selects option 1 after submission it will direct them to the Facebook page, if they select option 2 it will direct them to a youtube page .. etc
This is quite simple. You just have to get the value from the selector & use JS to open that link. Check my solution for reference -
solution on JS Fiddle
function myFunction() {
let link =
document.getElementById("social").value
let fb = "https://facebook.com"
let tw = "https://twitter.com"
if(link == 'fb') {
window.open(fb);
} else if (link == 'tw') {
window.open(tw);
}
}
<select id="social">
<option value="fb">Facebook</option>
<option value="tw">Twitter</option>
</select>
<button onclick="myFunction()">
go to site
</button>
This somehow doesn't work here, working on JS Fiddle
<body>
<form>
<select name="" id="target">
<option value="facebook">Facebook</option>
<option value="youtube">Youtube</option>
<option value="twitter">Twitter</option>
</select>
<button type="button" id="sub_button">submit</button>
</form>
<script>
const data = {
facebook: 'https://facebook.com',
youtube: 'https://youtube.com',
twitter: 'https://twitter.com',
}
document.querySelector('#sub_button').onclick = function() {
let target = document.querySelector('#target').value;
window.location.href = data[target];
}
</script>
</body>

How to change button URL through JS?

I have been spending a lot of time researching how to change a button href dynamically in my website using JS. I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.
I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.
One of the simplest solutions that should work was found here:
How to make option selection change button link?
I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed. I added window.onload() to prevent the JS from running before elements were loaded.
I am trying to do something similar with the following HTML & JS code:
HTML Code:
<input type="hidden" id="input-book-type" value="GlassCrystal">
<br><br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br><br>
<input id="input-project-title" value="Optional Project Title">
<br><br>
<a class="button" id="design-button" href="http://">Design Now</a>
JS Code:
window.onload = function() {
document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");
this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};
}
JS Fiddle:
https://jsfiddle.net/w65c9x2d/
I think your code to change the href is correct. However, the onload function is not immediately invoked for the code to work.
window.onload = function(e) {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var pagenum = document.getElementById("select-page-num");
var projtitle = document.getElementById("input-project-title");
document.getElementById("design-button").onclick = function() {
this.href = "http://design.framesmile.com/?sessionid=guest&ref=" + booktype.value + pagesize.value + "*projectName=" + projtitle.value + " / ";
console.log(this.href);
};
}();// invoke the function
<input type="hidden" id="input-book-type" type="" value="GlassCrystal">
<br>
<br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br>
<br>
<select id="select-page-num">
<option value="20">20</option>
<option value="22">22</option>
</select>
<br>
<br>
<input id="input-project-title" type="" value="Optional Project Title">
<br>
<br>
<a class="button" id="design-button" href="http://test/">Design Now</a>
Here is example code:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php";
return false;
};
</script>
I took this from here
Change your button to this:
<button class="button" id="design-button" onclick="redirect()">Design Now</button>
Now instead of using a link, simply do a function that will take the inputs and change the window.location.href (or whatever method you prefer) to change the page.
redirect(obj) {
window.location.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/"
}
Obviously change it to your liking :)
I recommend using jQuery.
$("#submit").on('click', function(event) {
event.preventDefault();
data = $("#link").val();
$("#frame").attr({
src: "http://"+data});
});
When the submit button is clicked, it changed the iframe url which changed the content of the iframe automatically.
I don't really understand what you are trying to ask, but try to modfiy the code above :)

trouble getting javascript global variable in function

I have checked all the other 'duplicate' questions on this. But have hit a wall in terms of finding what is wrong with my script. Could be something very simple. But I have run out of steam finding the fault. So I am here.
I am trying to create a product list on a web page with an 'Inquire' link for each product. On clicking the link, the product id is captured and a brief form for adding user contact details comes up. When the user submits the form, the inquired product details and user contact details are emailed to admin.
I am doing all this with JS with an Ajax Post call to a PHP file.
Everything is fine accept between the two functions
When 'Inquire' link is clicked
and
When form submit button is clicked.
My issue is, I am not able to pass the inquired product name variable 'item' to the submit function. In submit function I get 'item' undefined.
I am not too good at JS. I know I am making some procedural error. Would be great if somebody could point out what I am doing wrong.
My codes;
HTML
<div class="prodlist"><div class="productimg"><h4 id="itemcf">Cupellation Furnace</h4><img src="images/cupellation-furnace.png" alt="cupellation furnace"></div><div class="prodtxt"> This is the product description area. This area will contain details and specifications</div><div id="inquirecf"><span>Inquire</span></div><div id="inqrescf"></div></div>
<div class="prodlist"><div class="productimg"><h4 id="itemmf">Melting Furnace</h4><img src="images/furnace-2kg.png" alt="Melting furnace"></div><div class="prodtxt"> This is the product description area. This area will contain details and specifications</div><div id="inquiremf"><span>Inquire</span></div><div id="inqresmf"></div></div>
<div id="inqform">
<span id="inqclose">Close</span>
<div style="clear:both"></div>
<div id="inqresgen"></div>
<form id="forminq" method="post">
Name : <input type="text" id="inqname" require><br>
<div style="clear:both"></div>
phone : <input type="number" id="inqphone" require><br>
<div style="clear:both"></div>
Email : <input type="email" id="inqemail" require><br>
<div style="clear:both"></div>
Location : <input type="text" id="inqloc" require><br>
<div style="clear:both"></div>
Message : <textarea cols="30" rows="10" id="inqmsg" require></textarea>
<div style="clear:both"></div>
<input type="submit" onClick="sendInq();" value="Send">
<div style="clear:both"></div>
</form>
<div style="clear:both"></div>
</div>
JS
$(document).ready(function(){
var item;
$('#inqclose').click(function(){ $('#inqform').fadeOut('fast');});
$('#inquirecf,#inquiremf').click(function(){
var id = $(this).attr('id');
//alert(id);
if(id=="inquirecf"){alert("inquirecf"); item="Cupellation Furnace";}
else if(id=="inquiremf"){alert("inquiremf");item="Melting Furnace";}
else{alert("No Choices");}
$('#inqform').slideToggle('fast');
});
});
function sendInq(item){
var itemv=item;
event.preventDefault();
var inqname=$('#inqname').val();
var inqphone=$('#inqphone').val();
var inqemail=$('#inqemail').val();
var inqloc=$('#inqloc').val();
var inqmsg=$('#inqmsg').val();
alert("Item : "+ itemv);
$.post("inquire.php",
{
itemname: itemv,
inqname: inqname,
inqphone: inqphone,
inqemail: inqemail,
inqloc: inqloc,
inqmsg: inqmsg
},
function(data,status){
// alert("Data: " + data + "\nStatus: " + status);
$('#inqresgen').html( data );
///$('#inqres2').html( "<h4>Inquiry Sent</h4>");
$('#forminq').fadeOut('fast');
});
}
Well after a lot of googling and studying different options, I realized that the using
window.item
Helped
Now my code looks like
$('#inquirecf,#inquiremfhalfkg,#inquiremf1kg,#inquiremf2kg,
#inquiremf5kg,#inquirecupels,#inquiremuffles,#inquirecrucibles,#inquirethermo,
#inquiresilicon').click(function(){
var id = $(this).attr('id');
if(id=="inquirecf"){window.item="Cupellation Furnace";}
else if(id=="inquiremfhalfkg"){window.item="Melting Furnace 0.5Kg";}
else if(id=="inquiremf1kg"){window.item="Melting Furnace 1Kg";}
else if(id=="inquiremf2kg"){window.item="Melting Furnace 2Kg";}
else if(id=="inquiremf5kg"){window.item="Melting Furnace 5Kg";}
else if(id=="inquirecupels"){window.item="Cupels";}
else if(id=="inquiremuffles"){window.item="Muffles";}
else if(id=="inquirecrucibles"){window.item="Crucibles";}
else if(id=="inquirethermo"){window.item="Thermocouples";}
else if(id=="inquiresilicon"){window.item="Silicon Carbide Elements";}
else{alert("No Choices");}
}
function sendInq(item){
var itemv=window.item;
//......
}
All is well now. Thanks all for your efforts.

How to pass parameters to a URL from a select form?

I want to pass values from a select form to a URL in order to connect to an external website using iframe solutions.
I'm very to new to .PHP & JavaScript. Please help me out.
This is the form I created to get data from users to pass into a specific URL.
<form action="selectcourier.php" method="GET">
<h1>Select courier service</h1>
<select>
<option value="Select">Select Courier Service</option>
<option value="1">DTDC</option>
<option value="2">AFL</option>
<option value="3">BlueDart</option>
</select>
Consignment Number: <input type="text" name="cNum"><br>
<center><input type="submit"></center>
</form>
selectcourier.php
<body>
<form><center><h3> CONFIRM <h3></center>
<iframe id="ifrm" width=300 height=300 seamless src="http://example.com/">
</body>
My question:
Hope you have understood that I'm trying to give all courier tracking service right from my website using an iframe. But here I'm unable to differentiate the appropriate URLs for different types of Courier Service to pass the value (cNum) and open that web link in an iframe.
I have all the URLs of all courier services.
Now how can I differentiate them to pick up the appropriate URL when a Courier Service is selected by the User?
Kindly help me, please. Thanks.
Since you simply want to load a url to an iframe based on the selection, I would go with this. Basic explanation can be found in the comments:
<html lang="en">
<head>
<script type="text/javascript">
// Set global variables
var serviceSelect;
var ConNumberElement;
// Wait for the page to be loaded
document.addEventListener('DOMContentLoaded', function() {
// Get required elements
serviceSelect = document.getElementById("CourierService");
ConNumberElement = document.getElementById("cNum");
});
function loadWebsite(){
// Get the iframe
var ifrm = document.getElementById("ifrm");
// Get Consignment Number
var ConNumber = ConNumberElement.value;
// Get Courier Service
var serviceValue = serviceSelect.value;
// Make sure a correct service is selected
if(serviceValue == "1"){ // DTDC is selected
ifrm.src = "http://dtdc.com/tracking/tracking_results.asp?action=track&sec=tr&ctlActiveVal=1&Ttype=awb_no&strCnno=" + ConNumber + "&GES=N&TrkType2=awb_no&strCnno2=" + ConNumber;
} else if(serviceValue == "2"){ // AFL is selected
ifrm.src = ""; // Add the correct url here. Take the example above on how to do it.
} else if(serviceValue == "3"){ // BlueDart is selected
ifrm.src = ""; // Add the correct url here. Take the example above on how to do it.
} else {
alert("You have to select a correct Courier Service");
}
}
</script>
</head>
<body>
<h1>Select courier service</h1>
<select id="CourierService">
<option value="Select">Select Courier Service</option>
<option value="1">DTDC</option>
<option value="2">AFL</option>
<option value="3">BlueDart</option>
</select>
Consignment Number: <input type="text" id="cNum"><br>
<input type="button" onclick="loadWebsite();" value="CONFIRM" />
<iframe id="ifrm" width=300 height=300 seamless src="http://example.com/">
</body>
</html>

How to dynamically change the selected option and update without reloading?

It was hard to find terms for a good search (so please excuse me if the topic has already been discussed) as well as an explicit title for this post.
I'm working on this external web page : https://espacepersonnel.bnf.fr/views/mes_notices.jsf (need to be logged)
and I'm trying to override the default selected option with the one which value="0". The custom js code I wrote does submit the form but only after the page has been loaded. Nevertheless I'd like to change the select value before this.
Here's the concerned code's part of this page (that of course I can't edit) :
<form id="noticeComp:mainForm" name="noticeComp:mainForm" method="post" action="/views/mes_notices.jsf" class="noticeForm" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="noticeComp:mainForm" value="noticeComp:mainForm">
<input type="hidden" name="noticeComp:mainForm:j_idt253" value="">
<input type="hidden" name="noticeComp:mainForm:j_idt254" value="false">
<!-- <div id="site"> -->
<!-- <div class="moncatagen"> -->
<!-- <div class="col2"> -->
<h1 class="h1small">
<span>
<select name="noticeComp:mainForm:j_idt256" size="1" onchange="submit()">
<option value="0">Toutes les notices</option>
<option value="1" selected="selected">Notices biblio.</option>
<option value="2">Notices d'autorités</option>
</select>
Notices
</span>
</h1>
</form>
And here's my own 'content_script' :
var elm;
var evt;
elm = document.getElementsByName('noticeComp:mainForm:j_idt256')[0];
evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
while(!document.getElementsByName('noticeComp:mainForm:j_idt256')[0].options[0].selected){
document.getElementsByName('noticeComp:mainForm:j_idt256')[0].options[0].selected="selected";
elm.dispatchEvent(evt);
}
Can you see a solution for me ? (Better if JS only)
Thank you very much for reading this post and answering it if you can.
Bigindian.
P.S : Pardon my english
N.B :
Result page :
result page
You can try the following:
get a reference to the select
loop over its options
if the value of the option is '0', select it. Otherwise, deselect it.
Example code:
var elm = document.getElementsByName('noticeComp:mainForm:j_idt256')[0];
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
for (var i = 0; i < elm.options.length; i++) {
var option = elm.options[i];
if (option.value === '0') {
option.setAttribute('selected', 'selected');
} else {
option.removeAttribute('selected');
}
}
elm.dispatchEvent(evt);
function submit() {
// code
console.log('gogo');
}
demo

Categories