How to replace base url of a form action using JavaScript? - 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.

Related

Redirect on submit based on search query and location

I am trying to add a search feature based on a text input and a drop-down.
So I am trying to make it work with the following form fields:
Text input {text_1}
Drop-down (2 options)
Submit button
If first option is selected in the drop-down the form should be submitted to https://url1/?={text_1}, if second option is selected it should be submitted to https://url2/?={text_1}.
I have written so far:
<form>
<input type="text" id="text_1" name="text_1" value="test" data-alias="" class="form-control">
<select id="selectlist_1" name="selectlist_1" data-alias="" class="form-control">
<option value="option_1" >Option_1</option>
<option value="option_2" >Option_2</option>
</select>
<button type="submit" id="button_1" name="button_1" class="btn btn-primary" >Submit</button>
</form>
Otherwise, there is also this example: https://hii.com/careers/
I give you an example:
<script>
function go(v){
if (v.url.value===1){
v.action="http://www.google.com"
}else {
v.action="http://www.apple.com"
}
}
</script>
<form onsubmit="go(this)">
<input type="text" name="text_1" value="txt">
<select name="url">
<option value="1">Google</option>
<option value="2">Apple</option>
</select>
<input type="submit" value="submit">
</form>
Augment a simple form with the controls you want, with a script that sets up a behaviour where the form's action attribute value changes with the selection in the drop-down control:
<form>
<input name="foobar" />
<select name="fruit">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
</select>
<script>
(script => {
const fruit_control = script.closest("form").elements.fruit;
fruit_control.addEventListener("change", ev => {
ev.target.form.action = ({
"apples": "https://url_1",
"oranges": "https://url_2"
})[ev.target.value];
});
})(document.currentScript);
</script>
</form>
The value of the text input control will be sent with the query string, i.e. as ?foobar=... at the end of the URL, as the form is submitted, to the URL that's correspondent with the option selected in the drop-down.
Whether you have a submit button at the end of the form, or not, makes no difference to the behaviour of the form because a form may be submitted even without a submit button.
I found a working solution after doing some searches.
Here is solution in case anyone need it.
jQuery('#search_page_form').submit(function() {
// get all the inputs into an array.
var stext = jQuery('#search_page_form #looking-for').val();
var cars = jQuery('#search_page_form #cars').val();
var url = '';
if(cars == 'nns'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext;
}else if(cars == 'mt'){
var url = 'https://tsd-careers.hii.com/en-US/search?keywords='+stext;
}else if(cars == 'is'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext+'&locationsearch=Pascagoula%2C+MS&geolocation=';
}else if(cars == 'ch'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext+'&locationsearch=Newport+News%2C+VA&geolocation=';
}
if(url != ''){
window.open(url, '_blank');
}else{
alert('Please select Division');
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search_page_form" onsubmit="return false;">
<div class="form-group">
<label for="looking-for">What are you looking for ?</label>
<input type="text" id="looking-for" name="looking-for" class="form-control" placeholder="Enter keywords....">
</div>
<div class="form-group">
<select id="cars" name="cars" class="form-control nice-select">
<option selected="" value="">Division</option>
<option value="nns">NEWPORT NEWS SHIPBUILDING</option>
<option value="mt">MISSION TECHNOLOGIES</option>
<option value="is">INGALLS SHIPBUILDING</option>
<option value="ch">CORPORATE HEADQUARTERS</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="SEARCH" class="btn white-btn search_btn">
</div>
</form>

Is there a way to combine multiple search functions into a dropdown selection?

I have multiple search functions/text boxes that I would like to condense into a textbox + dropdown selection.
http://jsfiddle.net/rhnt9vme/3/
<div>
<form>
<input type='text' id='searchOneInput' />
<button type='submit' onclick='searchOne()' target="_blank">Search 1</button>
</form>
</div><br>
<div>
<form>
<input type='text' id='searchTwoInput' />
<button type='submit' onclick='searchTwo()' target="_blank">Search 2</button>
</form>
</div><br>
<div>
<form>
<input type='text' id='searchThreeInput' />
<button type='submit' onclick='searchThree()' target="_blank">Search 3</button>
</form>
</div><br>
function searchOne(){
var searchOneInput = document.getElementById('searchOneInput').value;
window.open("http://one.com/search=" + searchOneInput);
}
function searchTwo(){
var searchTwoInput = document.getElementById('searchTwoInput').value;
window.open("http://two.com/search=" + searchTwoInput);
}
function searchThree(){
var searchThreeInput = document.getElementById('searchThreeInput').value;
window.open("http://three.com/search=" + searchThreeInput);
}
I want to combine these into a dropdown selection single textbox search that looks like this:
<form>
<input type="text" id="userInput" />
<select id="dropdown">
<option value="">Search 1</option>
<option value="">Search 2</option>
<option value="">Search 3</option>
</select>
<button type="submit" onclick="">Search</button>
</form>
Set an ID to your form and listen for "submit" event using Element.addEventListener() method
Set the respective websites URL inside the <option>s value attribute
Don't forget to trim the user input, just in case of accidental wrapping whitespaces
document.getElementById("searchForm").addEventListener("submit", function(ev) {
ev.preventDefault(); // Comment out if not needed
var dropdownURL = document.getElementById("dropdown").value;
var searchInput = document.getElementById("userInput").value.trim();
var address = dropdownURL + searchInput;
console.log(address);
window.open(address);
});
<form id="searchForm"> <!-- PS: add ID to form -->
<input type="text" id="userInput">
<select id="dropdown">
<option value="http://one.com/?search=">Search 1</option>
<option value="http://two.com/?search=">Search 2</option>
<option value="http://three.com/?search=">Search 3</option>
</select>
<button type="submit">Search</button>
</form>
In case you need a combined URI string with additional suffixed query parameters like
https://example.com/?search=**USERINPUTHERE**&c=%2FDefault.asp
than you could use a placeholder in the set of not URI allowed characters, like |, and replace it with the user input string using String.prototype.replace()
document.getElementById("searchForm").addEventListener("submit", function(ev) {
ev.preventDefault(); // Comment out if not needed
var dropdownURL = document.getElementById("dropdown").value;
var searchInput = document.getElementById("userInput").value.trim();
// Replace "|" with the user input
var address = dropdownURL.replace(/\|/, searchInput);
console.log(address);
window.open(address);
});
<form id="searchForm"> <!-- PS: add ID to form -->
<input type="text" id="userInput">
<select id="dropdown">
<option value="http://one.com/?search=|">Search 1</option>
<option value="http://two.com/?search=|">Search 2</option>
<option value="http://three.com/?search=|">Search 3</option>
<option value="https://four.com/?search=|&c=%2FDefault.asp">Search 4</option>
</select>
<button type="submit">Search</button>
</form>
PS: since the order of query params is not important, you can always define your string like: https://example.com/?c=%2FDefault.asp&search= and use the first example anyways.

Submit select option and current page url parameter

I have webpage like: index.php/voting/?name=someName which has form with select options:
<form id="voting-form" method="GET" action="index.php/vote/">
<select name="company" id="company">
<option value="company1">company 1</option>
<option value="company2">company 2</option>
<option value="company3">company 3</option>
</select>
<input type="submit" value="Submit">
</form>
I need to submit this form with select value and url name parameter from current page. For example user chose company1: index.php/vote/?company=company1&name=someName
I tried to modify form action like this:
var url_string = window.location.href
var url = new URL(url_string);
var name = url.searchParams.get("name");
document.getElementById('voting-form').action = "index.php/vote/?name=" + name +"&";
But when I submit button, I am redirected to index.php/vote/?company=company1. so name param is missing
You can add to form input with type hidden to add this to url params
<input type="hidden" name="name" value"someName" id="nameInput">
To set value of input you can use your JS with a bit modification
var url = new URL(window.location.href),
name = url.searchParams.get("name");
document.getElementById('nameInput').value = name;
or PHP like in #Globus example
The form post doesn't care about your javascript, and does what it pleases.
You should create a hidden field in your form where you store the name in your GET parameter, so that the form submission also adds this parameter to the URL.
Change your code to:
<form id="voting-form" method="GET" action="index.php/vote/">
<select name="company" id="company">
<option value="company1">company 1</option>
<option value="company2">company 2</option>
<option value="company3">company 3</option>
</select>
<input name="name" value=<?=$_GET['name']?> type="hidden" />
<input type="submit" value="Submit">
</form>

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));

Trying to redirect with 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();" />

Categories