Trying to redirect with javascript - javascript

I'm very new to javascript and I'm trying to make different events occur depending on types of input. I have the following in my html header:
<script type="text/javascript">
function validateForm(){
var val=document.getElementsByName("destination");
if (val == "deprecated"){
window.location="http://website.com/";
}
}
</script>
Then in the body, I have the following:
<select name="destination">
<option value="current_builds">Current Builds</option>
<option value="deprecated">Deprecated Files</option>
<option value="mailing_list">Mailing List</option>
</select><br/>
<input type="button" value="next >" onClick="validateForm()" />
This however doesn't do anything. It just stays on the same page. I also tried wrapping it inside a form tag by saying:
<form name="my_form" onSubmit="validateForm()">
...
</form>
and then having matching javascript:
var val = document.forms["my_form"]["destination"].value
But this didn't work either.
Anyone see what the issue is?
Thanks.

I fixed your function and tested it:
function validateForm(){
var val=document.getElementsByName("destination");
var theSelectedOption = val[0].options[val[0].selectedIndex].value;
if (theSelectedOption == "deprecated"){
window.location="http://website.com/";
}
}

You need to grab the value from the selected element. Since document.getElementsByName returns an array, try using this
var val = ​document.getElementsByName("destination")​​​​​[0].value

You need to get the value from the selected option. Like so:
var index = document.getElementsByName("destination").selectedIndex;
var val=document.getElementsByName("destination").options[index].value;
That will retrieve the value of the selected option.

You're missing the href attribute, you want to use:
window.location.href = 'URL';

do the following
<select name="destination" id="destination">
Your JavaScript
val=document.getElementsById("destination").value;
Put an alert(val) in your if to see if ever evaluates to true

Try this with a little bit of jquery
Redirect using drop down
<form name="my_form">
<select id="destination">
<option value="current_builds">Current Builds</option>
<option value="deprecated">Deprecated Files</option>
<option value="mailing_list">Mailing List</option>
</select><br/>
<input type="button" value="next >" id="submit">
</form>
​
$('#submit').click(
function validateForm(){
var e = document.getElementById("destination");
var val = e.options[e.selectedIndex].value;
if (val == "deprecated"){
window.location="http://website.com/";
}
});

Try it with id's instead of name, an id is a unique element. Javascript supports
var destination = document.getElementById("destination");
if (destination.options[destination.selectedIndex].value == "deprecated"){
window.location="http://website.com/";
}
HTML
<select id="destination">
<option value="current_builds">Current Builds</option>
<option value="deprecated">Deprecated Files</option>
<option value="mailing_list">Mailing List</option>
</select>
<br />
<input type="button" value="next >" onclick="javascript:validateForm();" />

Related

How to replace base url of a form action using JavaScript?

I'm trying to make a simple search for Wikipedia where I can type what I want to search and a select where I can select the language. What I'm trying to do is to get the select value to be able to search in different languages so I just replace the language string in the url of wikipedia.org
(e.g. If I select French in the select dropdown the form should redirects me to fr.wikipedia.org and if I select English, it should redirects me to en.wikipedia.org)
Here's what I tried so far:
<form id="searchWikipedia" action="" onsubmit="searchWikipedia()">
<input id="search" name="search" type="text" />
<select id="lang" name="language">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</form>
<script>
function searchWikipedia() {
var select = document.getElementById("lang");
var selectValue = select.options[select.selectedIndex].value;
var searchValue = document.getElementById("search").value;
document.getElementById("searchWikipedia").action = selectValue + ".wikipedia.org/w/index.php?search=" + searchValue;
document.getElementById("searchWikipedia").submit();
}
</script>
Now, on submit I get this url: http://localhost/en.wikipedia.org/w/?search=cat
What I'm expecting is that the browser should redirect to en.wikipedia.org/w/?search=cat
How can I replace base url of a form action using JavaScript? Are there any better methods of doing this?
you need to append the protocol at the start of the url or the browser will take it as a relative url to your document.
<form id="searchWikipedia" action="" onsubmit="searchWikipedia()">
<input id="search" name="search" type="text" />
<select id="lang" name="language">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</form>
<script>
function searchWikipedia() {
var select = document.getElementById("lang");
var selectValue = select.options[select.selectedIndex].value;
var searchValue = document.getElementById("search").value;
// append https at the start
document.getElementById("searchWikipedia").action = "https://" + selectValue + ".wikipedia.org/w/index.php?search=" + searchValue;
document.getElementById("searchWikipedia").submit();
}
</script>
Add Submit input tag, to perform action
<form id="searchWikipedia" action="" onsubmit="searchWikipedia(event)">
<input id="search" name="search" type="text" />
<select id="lang" name="language">
<option value="en">English</option>
<option value="fr">French</option>
</select>
<input type="submit" value="Search">
</form>
<script>
function searchWikipedia(event) {
event.preventDefault();
var select = document.getElementById("lang");
var selectValue = select.options[select.selectedIndex].value;
var searchValue = document.getElementById("search").value;
// it will open new tab
window.open("https://" + selectValue + ".wikipedia.org/w/index.php?search=" + searchValue);
// if you want to replace same url then use this
// window.location.replace(`https://${selectValue}.wikipedia.org/w/index.php?search=${searchValue}`);
}
</script>
I think, it will be helpful for you.

how to create dynamic javascript function

When I choice google the submit button value turn into google.com and I choice yahoo submit button value will be change. Here is my attempt.
<script>
function goToNewPage() {
if(document.getElementById('target').value){
window.open('url','_blank');
}
}
</script>
<form name="dropdown">
<select name="selected" id="target" accesskey="E">
<option selected>...Select...</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com/">Yahoo</option>
</select>
<input type="button" value="Go" onclick="goToNewPage(document.dropdown.selected)">
</form>
You were VERY close.
This edited version fixes it. (fiddle)
HTML - Add value for nothing selected. Strip out the attempt at setting the URL on the way in. Added an ID for the button, to be used for new function.
<form name="dropdown">
<select name="selected" id="target" accesskey="E" onchange="changeText()">
<option value="nothing" selected>...Select...</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com/">Yahoo</option>
</select>
<input type="button" value="Go" id="butGo" onclick="goToNewPage()">
</form>
JS - Set URL when the function is called. Don't put URL in quotes. It would think it's a string.
function goToNewPage() {
url = document.getElementById('target').value;
//alert(url)
if(document.getElementById('target').value!='nothing'){
window.open(url,'_blank');
}
}
If you want to change the TEXT on the button, do this:
function changeText(){
url = document.getElementById('target').value;
if (url=='http://www.google.com') {
document.getElementById('butGo').value = 'Google'
}
if (url=='http://www.yahoo.com/') {
document.getElementById('butGo').value = 'Yahoo'
}
}

How to take hidden input from inside option in HTML

Due to some requirement, I have to take a hidden input field inside option tag of select element. The problem I'm facing is, when the selected value is displayed, it's displayed with prefix >.
Here's my code:
<form action="Action.java">
<select name="cars">
<option value="car1" <input type="hidden" id="hidden" value="c1">>CAR1</option>
<option value="car2">CAR2</option>
<option value="car3">CAR3</option>
</select>
<input type="submit" value="Submit">
</form>
Can anyone help me fix this issue?
As others have mentioned, this line:
<option value="car1" <input type="hidden" id="hidden" value="c1">>CAR1</option>
isn't valid html. Your browser is closing your optinput™ - and is then seeing an extra '>'
You could do this sort of thing (untested code):
<form id="my_select">
<select name="cars">
<option value="car1">CAR1</option>
<option value="car2">CAR2</option>
<option value="car3">CAR3</option>
</select>
<input type="hidden" id="hidden" value="">
<input type="submit" value="Submit">
</form>
<script>
$("#my_select").change(function() {
var str = "";
$("select option:selected").each(function() {
str += $(this).text() + " ";
});
$('#hidden').val(str);
}).change();
</script>
However, AND I CANT STRESS THIS ENOUGH: Don't.
Whatever your reason for needing to set that hidden field - do it in you back end code i.e (psuedo)
if (cars === car1) {
c1 = true
}
But do you really need to set it?

Change form action based on drop down selection

Need form to change it's action depending on the selection from a specific drop down menu.
On change should trigger the script and change the action before user submits. Easier said than done when you're new to JS.. thanks for any help!
Javascript:
<script type="application/javascript">
function chgAction(form1){
if( recipient=="jordachedotcom_Advertising" )
{document.form1.action = "/adv_contact.php";}
else if( recipient=="dept_Public_Relations" )
{document.form1.action = "/pr_contact.php";}
else if( recipient=="dept_Manufacturing" )
{document.form1.action = "/manuf_contact.php";}
else if( recipient=="dept_Brands" )
{document.form1.action = "/brands_contact.php";}
else if( recipient=="dept_Holdings" )
{document.form1.action = "/holdings_contact.php";}
else if( recipient=="dept_Vendor_Inquiry" )
{document.form1.action = "/vend_contact.php";}
else if( recipient=="dept_Other_Inquiry" )
{document.form1.action = "/misc_contact.php";}
}
</script>
FORM HTML:
<form id="form1" name="form1" method="post" action="/">
Please choose a dept:<br/>
<select name="recipient" id="recipient" size="1" onChange="javascript:chgAction()">
<option value="" selected="selected">Select</option>
<option value="dept_Advertising">Advertising</option>
<option value="dept_Public_Relations">Public Relations</option>
<option value="dept_Manufacturing">Manufacturing</option>
<option value="dept_Brands">Brands</option>
<option value="dept_Holdings">Holdings</option>
<option value="dept_Vendor_Inquiry">Vendor Inquiry</option>
<option value="dept_Other_Inquiry">Other Inquiry</option>
</select>
<input type="submit">
</form>
Your code is missing the part to get the selected item from the selectbox.
document.form1.recipient.selectedIndex
The rest should be ok and i have created a Fiddle
I'm guessing as to your full intent, but I think that the best way to accomplish what you're doing here would be via php on the server side. Have the form direct to one particular page and then using your server-side language redirect to the proper url. For example, if you're using php do something like this:
client-side (html)
(note how the action property of the form is one fixed location)
<form id="form1" name="form1" method="post" action="./form-handler.php">
Please choose a dept:<br/>
<select name="recipient" id="recipient" size="1">
<option value="" selected="selected">Select</option>
<option value="dept_Advertising">Advertising</option>
<option value="dept_Public_Relations">Public Relations</option>
<option value="dept_Manufacturing">Manufacturing</option>
<option value="dept_Brands">Brands</option>
<option value="dept_Holdings">Holdings</option>
<option value="dept_Vendor_Inquiry">Vendor Inquiry</option>
<option value="dept_Other_Inquiry">Other Inquiry</option>
<select>
<input type="submit">
</form>
No javascript required!
server-side (php)
form-hander.php:
<?php
$recipient = $_POST['recipient'];
//Based on the value of the $recipient value redirect to the correct page
//using the header function
switch($recipient) {
case 'dept_Manufacturing':
header('Location: ./manuf_contact.php'); exit;
case 'dept_Brands':
header('Location: ./brands_contact.php'); exit;
case 'dept_Holdings':
header('Location: ./holdings_contact.php'); exit;
//... etc, etc
}
On your on change function, you can obtain your currently selected element using:-
var currentValue = $("#recipient option:selected").val();
And then apply these if checks as you specified on this currentValue var as shown below:-
if(currentValue == "dept_advertising"){
$("#form1").attr("action",customURL);
}
Try this
<form id="form1" name="form1" method="post" action="/">
Please choose a dept:<br/>
<select name="recipient" id="recipient" size="1" onChange="javascript:chgAction()">
<option value="" selected="selected">Select</option>
<option data-action="/adv_contact.php" value="dept_Advertising">Advertising</option>
<option data-action="/pr_contact.php" value="dept_Public_Relations">Public Relations</option>
<option data-action="/manuf_contact.php" value="dept_Manufacturing">Manufacturing</option>
<option data-action="/brands_contact.php" value="dept_Brands">Brands</option>
<option data-action="/holdings_contact.php" value="dept_Holdings">Holdings</option>
<option data-action="/vend_contact.php" value="dept_Vendor_Inquiry">Vendor Inquiry</option>
<option data-action="/misc_contact.php" value="dept_Other_Inquiry">Other Inquiry</option>
</select>
<input type="submit">
</form>
<script>
function chgAction(){
$('#form1').attr({'action':$('option:selected').attr('data-action')});
$('#form1').submit();
}
</script>
You could also just use the actual form action URLs as the option values and use a simple one line onchange attribute without any additional JS:
<form method="post" name="form1">
<select id="form_action" name="form_action" onchange="document.form1.action = this.value;">
<option value="https://url1.com">URL1</option>
<option value="https://url2.com">URL2</option>
</select>
</form>
Tested and working in Firefox. May possibly benefit from some measures to make it more cross-browser compatible.
Replace:
function chgAction(form1){...}
in
chgAction = function(form1) {....}
Code will work but it is not the ultimate dream. Better to use something like that:
(function(){
var form = document.querySelector('#form1'),
select = form.querySelector('#recipient'),
action = {
'jordachedotcom_Advertising': '/adv_contact.php',
'dept_Public_Relations': '/pr_contact.php',
'dept_Manufacturing': '/manuf_contact.php',
'dept_Brands': '/brands_contact.php',
'dept_Holdings': '/holdings_contact.php',
'dept_Vendor_Inquiry': '/vend_contact.php',
'dept_Other_Inquiry': '/misc_contact.php'
};
select.addEventListener('change', function () {
var el = this, value = el.value;
if (action[value]) {
form.action = action[value];
}
}, false);}());
Like jQuery:
(function($){
var form = $('#form1'),
select = $('#recipient'),
action = {
'jordachedotcom_Advertising': '/adv_contact.php',
'dept_Public_Relations': '/pr_contact.php',
'dept_Manufacturing': '/manuf_contact.php',
'dept_Brands': '/brands_contact.php',
'dept_Holdings': '/holdings_contact.php',
'dept_Vendor_Inquiry': '/vend_contact.php',
'dept_Other_Inquiry': '/misc_contact.php'
};
select.on('change', function () {
var el = $(this), value = el.val();
if (action[value]) {
form.attr('action', action[value]);
}
});}(jQuery));

jquery check if option is selected

I am having a situation where i need to see if an option is selected or not.When i click a button, if an option is not selected, the select box should turn red and give me an alert. It does not work. I am having difficaulty with the if statement. Any solution?
Javascript
$(document).ready(function(){
var $films = [];
$("#button").click(function(){
var $titelBetyg = [];
var $titel = $('#name').val();
var $betyg = $('#options').val();
if($titel == ""){
$('#name').css('background-color', 'red');
alert("Fail");
}
else if($betyg == "0"){
$('#options').css('background-color', 'red');
alert("Fail");
}
else{
$titelBetyg.push($titel);
$titelBetyg.push($betyg);
$films.push($titelBetyg);
}
$('#rightbar').append($films);
});
});
HTML
<body>
<div id="page">
<div id="header">
<h1> Min filminsamling </h1>
</div>
<div id="leftbar">
<form>
<fieldset>
<legend>Lägg till en film:</legend>
Titel:
<br><input type="text" name="name" id="name"><br>
Betyg:
<br><select id="options">
<option>Välj betyg här...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br><input type="button" name="button" value="Spara film" id="button">
</fieldset>
<fieldset>
<legend>Sortera film:</legend>
<input type="button" name="stigande" value="Högst betyg" id="stigande">
<br><input type="button" name="fallande" value="Lägst betyg" id="fallande">
</fieldset>
</form>
</div>
<div id="rightbar">
Filmer
</div>
</div>
</body>
$betyg == "0" isn't working because it isn't a possibility according to the UI.
Your default option is... nothing. Perhaps an empty string, ""; nowhere does 0 appear.
Explicitly set an option to check for, and check for it.
When you check whether to warn that nothing is selected, you look to see if the value of "option" is "0". Yet you didn't actually define the value of "0" for no selection, you only defined values "1" through "5". I'm not sure what to expect with Javascript if you ask for the value of something whose value is undefined; my first suggestion would be to define the value "0" for no selection and see if it helps. :)

Categories