I have a bit of experience with HTML but am very new to JavaScript. In essence, I would like for a user input to be part of a URL. For example, we could have something simple such as:
<script>
function get_cityname() {
var cityname = document.getElementById("cn").value;
alert(cityname);
}
</script>
<form>
Enter city name:
<input type = "text" size = "12" id = "cn">
<input type = "submit" onclick = "get_cityname();">
</form>
This will create a textbox where a user inputs their text (city name) and then click the 'submit' button next to it, and an alert should pop up based on the information they provided, just to make sure this works. However, this code only would seem to work (because of the 'onclick' command) to work for one user input. Therefore, I have 2 questions:
How could the above variable be included in a URL string? If it were something simple as:
URLstring = "https://sampleurl" + cityname + "moretext.html"
How could this be expanded if I want to include two or possibly even n number of inputs? For example, if I create more user prompt boxes and want to have the user also be able to input their zipcode, or state abbreviation, for example:
URLstring = "https://sampleurl" + cityname + "moretext" + zipcode + "moretext" + "stateabbreviation.html"
You could do something along these lines (it would be the same for one or more fields):
// Ensures the DOM (html) is loaded before trying to use the elements
window.addEventListener('DOMContentLoaded', function() {
var cnInput = document.getElementById("cn"),
zipInput = document.getElementById("zip"),
form = document.getElementById("myForm");
form.addEventListener('submit', getUrl); // On submit btn click, or pressing Enter
function getUrl(e) {
var cityname = cnInput.value,
zipcode = zipInput.value,
url = "https://sample.com/" + cityname + "/" + zipcode + ".html";
alert(url);
e.preventDefault(); // Prevent the form from redirecting?
}
});
<form id="myForm">
<label>Enter city name: <input type="text" size="12" id="cn"></label>
<label>Enter zip code: <input type="text" size="12" id="zip"></label>
<input type="submit">
</form>
First specify an action attribute for your form. This is where your form will be submitted. Then set your form's method attribute to GET. Finally, add as many fields as you like (I am assuming you are after a GET query such as https:url.com?key1=val1&key2=val2...):
<form method="GET" action="https://sampleurl">
Enter city name:
<input type="text" size="12" id="cn">
Enter zip code:
<input type="text" pattern="[0-9]{5}"
<input type="submit" ">
</form>
Related
I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>
my simple html file code
Site Name: <input id="name" type="text" onkeyup="myFunction1(event,this)">
URL : <input id="url" type="text">
javascript code
function myFunction1(event,t){
var nameval= document.getElementById("name").value;
var urlval= document.getElementById("url").value;
var namelen = nameval.length;
var urllen = urlval.length;
var res = nameval.substring(1, namelen);
if(res.length == urllen){
document.getElementById("url").value = t.value;
}
else{
alert("string lengths are not matching");
}
}
what i want to do when user type Site Name in textbox, same text should reflect to URL textbox if name and url text boxes have same text lenghts . but when i speed type site name, my if condition fail after typing few characters and it goes to else block. i dont know why this happening. can anyone help me to improve this code?
Using the onkeyup event isn't your best option for what you are trying to do. You can use the oninput event instead. Here's the modified HTML:
Site Name: <input id="name" type="text" oninput="myFunction1(event,this)">
URL : <input id="url" type="text">
What would be the best way to prepend text to an input value on form submit? I’m presuming Javascript?
I have an input on a form where the user will add a numeric value, but on submit I want the value to be prepended with the test 'Invoice Number ';
Don't know if it's the best way, but I would do something like this (untested):
<script>
function PerpendText(name) {
var val = document.getElementsByName(name)[0];
val.value = "Invoice Number:" + val.value;
}
</script>
<form onsubmit="PerpendText('num')">
Enter invoice number: <input type="text" name="num">
<input type="submit">
</form>
Here's a JSFiddle.
I'm not sure if this is possible, or if I am doing it the wrong way?
I have a form that when submitted, should send the user to a URL depending on the input.
e.g If the users inputs '2', the URL should be books/itemView?id=2
I have created a var = id, which takes the search input box data. Is it possible to add this variable to my current form action? Perhaps there is a more efficient way?
My current code is as follows;
<form id="search" action="<?php echo URL; ?>books/itemView?id=" method="post">
<input type="text" name="search" id="demo"/>
<input type="submit" value="Submit">
</form>
My JS
$(document).ready(function(){
var id = $('#search').val();
});
Quite new to JS so any help appreciated.
JS should be
$('#search').on('submit', function() {
var id = $('#demo').val();
var formAction = $('#search').attr('action');
$('#search').attr('action', formAction + id);
});
If they enter 2 in the search input then your id will be appended to your url like:
url?search=2
So maybe you want to change the name of your search input to id or add another input field.
<form id="search" action="<?php echo URL; ?>books/itemView" method="post">
<input type="text" name="id" id="demo"/>
<input type="submit" value="Submit">
</form>
That should be all you need no jquery or javascript necessary.
When you submit it should result in:
books/itemView?id=2(or whatever is in the search/id input when you click submit)
Hmm, you can try with that:
$(document).ready(function(){
var $form = $('#search');
var id = $form.val();
var $search = $('#demo');
var originalAction = $search.attr('action');
$form.on('submit', function() {
$search.attr('action', originalAction + id);
});
});
Before submitting the form, jQuery's on('submit', handler) function executes the code in handler modifying the attribute action that you want.
originalAction variable stores the content of the action attribute that was partially generated in php, then you append your id dynamically created with js.
i have a form which user enters some data, could be checkboxes, radio buttons, textfields, etc
when user click submit button, i want to refresh the page with whatever data that was entered
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
</head>
<body id="ref">
<form>
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
</form>
<input type="button" onclick="c()" value="submit">
<script type="text/javascript">
function c()
{
var o = document.getElementById('ref');
o.innerHTML = '';
var n = document.createElement('p');
var nam = document.getElementById('name');
n.innerHTML = "Your name is: " + nam;
o.appendChild(n);
var a = document.createElement('p');
var ag = document.getElementById('age');
a.innerHTML = "Your age is: " + ag;
o.appendChild(a);
//how do i get the info from the form? because both nam and ag are coming up null
}
</script>
</body>
</html>
my guess this is not working is because the page refreshes then tries to fetch the element by id which is not there anymore.. whats the correct way of doing this??
You're confusing objects with their properties. Here, you're getting the HTMLInputElement instance for the "age" field:
var ag = document.getElementById('age');
But here you're using that object as though it were a simple value:
a.innerHTML = "Your age is: " + ag;
The HTMLInputElement object has a value field you can use for that:
a.innerHTML = "Your age is: " + ag.value;
Separately, you're completely destroying the page by doing this:
var o = document.getElementById('ref');
o.innerHTML = '';
...because you've given the body element the ID "ref". Completely replacing the body element completely replaces the body element, so you can't rely on objects that only exist as subordinates of that element.
The usual thing is to have an element to fill in, and (optionally) to remove the elements you no longer need. For instance (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
<div id="result">
</div>
(Note I moved the button into the form for convenience.)
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result = document.getElementById("result");
form.parentNode.removeChild(form);
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
}
There, when the button is pressed, I remove the form and fill in the "result" div.
You could add the "result" div dynamically if you wanted (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
You can access the fields using a briefer and somewhat more natural syntax if you change your id values to name values instead (live copy):
HTML:
<form name="theForm">
Please enter your name:<input type="text" name="name" />
Please enter your age:<input type="text" name="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.theForm,
nameField = form.name,
ageField = form.age,
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
Further reading:
DOM2 Core (well-supported by most modern browsers)
DOM2 HTML
DOM3 Core (increasingly supported)
If you want to update your html using java-script only , you may use ".value" attribute of the input;
var a = document.createElement('p').value;
var ag = document.getElementById('age').value;
Usually the Form information is processed using server-side code , this is done by specifying the action attribute of the form:
<form action="processuserinfo.aspx">
...
</form>
I'm pretty sure this isn't doable javascript alone. You'll need to use a server-side language like php. Try to google php forms, and you should get some good results. :)