How to set the value of a form element using Javascript? - javascript

I have a simple form like this one:
<form ENCTYPE="multipart/form-data" action="upload.php" method="POST">
<p>UPLOAD FILE: <input type="file" name="file1"> <br /></p>
<input type="submit" value="Upload">
<input type="hidden" name="email" id="email" value="">
</form>
I have to set the value of the hidden field to an email like "email#email.com".
I can obtain this value from adding a querystring parameter by external iframe like:
<iframe name="email#email.com" src="index.html?email=email#email.com">
Ok. But how can I set value="" to value="email#email.com"?
I know have to use javascript, but I dunno how to deal with the var.

document.getElementById('Id').value='new value';
answer to comment:
try this:
<input type="" name="email" id="email">
<iframe id="frm" name="email#email.com" src="index.html?email=email#email.com">
</iframe>
<script>
document.getElementById('email').value = document.getElementById('frm').name;
</script>
then you can change adopt it. change type to hidden and etc.

If your script is executed from the document inside the iframe, you can do this :
var getUrlParameter = function(name, defaultValue) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( document.location.href );
if( results == null ) return defaultValue;
else return decodeURIComponent(results[1]);
};
document.getElementById('email').value=getUrlParameter('email');

As you've labeled this question as jQuery You can use $('#Id').val('new value'); But don't forget to add jQuery Library.

Related

How to replace characters while writing in a form?

The goal is to replace some characters directly when written in the form input, not after submitting the form. Also, I would like to change the contrast of the replacing character to be kind of grey/less visible.
I came up with something like that (but not working infortunately):
<form action="" method="post">
<input type="text" name="test_input" id="test_input" onkeypress="myFunction()" required>
<input type="submit" value="Subscribe!">
</form>
<script>
function myFunction() {
let str = document.getElementById("test_input").innerHTML;
let res = str.replace(/a/g, "b");
document.getElementById("test_input").innerHTML = res;
}
</script>
You have some mistakes in your code. Check out corrected code.
You need to correct your pattern.
<form action="" method="post">
<input type="text" name="test_input" id="test_input" onkeyup="myFunction()" required>
<input type="submit" value="Subscribe!">
</form>
<script>
function myFunction() {
let str = document.getElementById("test_input").value;
let res = str.replace(/a/g, "b");
console.log(res)
document.getElementById("test_input").value = res;
}
</script>
Try a cleaner solution that uses regular expressions:
<input type="text" onkeyup="this.value=this.value.replace(/[Search Expression]/flag,'New String');"/>
This solution prevents the user from typing a value outside the pattern established by the regex.
Example:
To remove all the numbers from "name" field:
<input type="text" onkeyup="this.value=this.value.replace(/[\d]/g, '');">

Change the URL with a GET method

is there a way to submit some selected fields to the URL with a GET method ?
by clicking on a button, I want to put a string on the URL, but using a GET method.
expected result:
test.html?test=11,13,21,34&somewords=1,2,3&demo=2
A simple form would most likely do
<form action="test.html" method="GET">
<input type="text" name="test">
<input type="text" name="somewords">
<input type="text" name="2">
<input type="submit">
</form>
Yes! Example :
function submit() {
var test = document.getElementById('test').value;
var demo = document.getElementById('demo').value;
var somewords = document.getElementById('somewords').value;
var url = 'test.html?test=' +test + '&somewords=' + somewords + '&demo=' + demo;
console.log(url); // test.html?test=1,2,3,4&somewords=noting&demo=2
// Code for get request
}
HTML
<input type="text" value="1,2,3,4" id="test">
<input type="text" value="noting" id="somewords">
<input type="text" value="noting" id="dummy">
<input type="text" value="2" id="demo">
<button onclick="submit()">Submit</button>
Live example : https://jsbin.com/cayude/edit?html,js,console,output
Hope this helps. Thanks !
If you are only interested in changing the displayed URL, use History#pushState.
history.pushState(null, null, formatURL(query));
If you actually want to navigate to a different page,
window.location.href = formatURL(query);
Assuming formatURL is a small helper utility that formats a querystring URL like what you've provided.

Dynamic URL from user input to search

What I am trying to accomplish: When a user inputs dates, number of adults ect it would dynamically add the info via javascript to the URL within the url variables. This is what I have so far: ( I am a Noob but trying to make it work )
<script type="text/javascript">
$(function () {
$('#submit').click(function() {
$('#button').click(function(e) {
var checkInDate = document.getElementById('checkInDate').value;
var checkInMonthYear = document.getElementById('checkInMonthYear').value;
var checkOutDate = document.getElementById('checkOutDate').value;
var checkOutMonthYear = document.getElementById('checkOutMonthYear').value;
var numberOfAdults = document.getElementById('numberOfAdults').value;
var rateCode = document.getElementById('rateCode').value
window.location.replace("http://www.Link.com/redirect?path=hd&brandCode=cv&localeCode=en&regionCode=1&hotelCode=DISCV&checkInDate=27&checkInMonthYear=002016&checkOutDate=28&checkOutMonthYear=002016&numberOfAdults=2&rateCode=11223");
window.location = url;
});
});
Ok, so first things first: You probably don't need to do this at all. If you create a form and add a name attribute to each input, then the submission automatically creates the URL for you. Fixed value fields can be set to type="hidden".
For this to work you need to use the "GET" method.
<form action="http://www.Link.com/redirect" method="GET">
<input type="hidden" name="path" value="hd"><br>
<input type="hidden" name="brandCode" value="cv"><br>
<input type="hidden" name="localeCode" value="en"><br>
<input type="hidden" name="regionCode" value="1"><br>
<input type="hidden" name="hotelCode" value="DISCV"><br>
<input type="text" name="checkInDate"><br>
<input type="text" name="checkInMonthYear"><br>
<input type="text" name="checkOutDate"><br>
<input type="text" name="checkOutMonthYear"><br>
<input type="text" name="numberOfAdults"><br>
<input type="text" name="rateCode"><br>
<input type="submit">
</form>
Clicking "Submit" changes the URL to the desired one.
If this does not suit your needs, you can replace parameters in the URL by following the advice in this SO answer: Answer Link
This is much better than trying to re-implement URL manipulation on your own.

Add post variable to form with jQuery

I have the below code which adds the value of the parameter to my form by default. This works well but if you set the form to post then it no longer works. What is the best approach to setting this value?
var request = {};
var pairs = location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0]] = pair[1];
}
var getfirstname = document.getElementById('firstname');
var firstname = request['firstname'];
getfirstname.setAttribute('value', firstname);
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
www.example.com?firstname=john
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" value="John" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
The answers you've gotten so far probably don't address your issue correctly. If you are setting the value of an input from a form that is submitted with the method set to "GET" then the parameters are available in the querystring and accessible by the browser - that's why this works:
var pairs = location.search.substring(1).split('&');
But when you change the method to "POST", the posted data is no longer available to the browser (client-side). You need to retrieve the posted data on the server-side. If you are using PHP you would do something like this (very very simplified version):
<?php
$firstname = (isset($_POST['firstname'])) ? $_POST['firstname']:'NA';
?>
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname; ?>" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
Hope that helps. If you can explain a little more about what you are trying to do I could add something to address an ajax via jQuery option.
If you want to set the value of a field set the value property not the value attribute
getfirstname.value = firstname;
Instead of setting the value attribute, set the actual value:
getfirstname.val(firstname);

Jquery get form field value

I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>

Categories