Please excuse my inexperience as I am not a programmer just someone who dabbles at trying to make something work. I'm not sure of the correct terminology and complicated explanations will go straight over my head!
In essence I am trying to get part of the URL of a web page passed to a simple Form that is linked to a shopping cart. i.e. how do I get the filename into the form where I have xxxxxxx. Is it possible in Javascript?
<script type="text/javascript">
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
document.write (filename);
</script>
<form action="http://www.mywebspace.com/cf/add.cfm" method="post">
<input type="hidden" name="userid" value="12345678">
<input type="hidden" name="product" value="xxxxxxx">
<input type="hidden" name="price" value="5.00">
<input type="Submit" value="Buy now!">
</form>
I've provided a snippet code that will work with your current HTML structure. Though I do suggest you give the product field an id to prevent the necessity to loop and search elements:
var url = window.location.pathname,
filename = url.substring(url.lastIndexOf('/')+1);
fields = document.getElementsByTagName('input');
for(var i = 0; i < fields.length; i++){
if(fields[i].name == 'product') {
fields[i].value = filename;
break;
}
}
If the form only exists once on a given page, this is an easy solution:
Change it to be:
<input type="hidden" id="productField" name="product" value="xxxxxxx">
In your javascript,
document.getElementById('productField').value = filename;
Yes this is possible.
Instead of doing document.write you need to update the form. Assuming your filename value is currently correct:
//js
document.getElementById( "name-of-file").value = filename;
<!- html -->
...
...
Related
Im working on a project with MVC and i'd like to know if there's a way to store the id of an input, which is a value received from one of my model items, into one of my JS variables
here's how the id of the input is being adressed
#foreach (var item in Model) {
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
}
and here's what i been trying to do in my .JS file
var id = document.getElementById('#item.id').value;
var nome = document.getElementById('#item.nome').value;
var preco = document.getElementById('#item.price').value;
You can use css class to mark elements where you want to store the id
select all elements with that css class using js
read id attribute for each element using loop
store it the way you need, eg. an array
Well, if you try this you see that your values are saved.
let id = document.getElementById('Id').value;
let name = document.getElementById('Name').value;
let price = document.getElementById('Price').value;
console.log(id);
console.log(name);
console.log(price);
but i somehow fail to use them in html. This doesn't work for example.
<script>
document.getElementById('Id').innerHTML = id;
document.getElementById('Name').innerHTML = name;
document.getElementById('Price').innerHTML = price;
</script>
<h1 id="Id"></h1>
<h1 id="Name"></h1>
<h1 id="Price"></h1>
It's maybe because the input is hidden.
Method 1
Well you can just expose that item ID directly to JavaScript
<script>
// this must be in the .html file, using window makes the variable global
// most rendering frameworks don't do conditional/server side rendering on static js files
window.ITEM_DATA = {
itemId: "#item.id"
}
</script>
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
Method 2
Alternatively, you can give each input a class and select all of the classes (or all of the inputs with type hidden)
<input type="hidden" value="#item.id" id="#item.id" class="item-data">
<input type="hidden" value="#item.nome" id="#item.nome" class="item-data">
<input type="hidden" value="#item.preco" id="#item.preco" class="item-data">
// this could be in its own file because we aren't relying on the server
// this is client-side js
const [itemId, itemNome, itemPreco] = document.querySelectorAll(".item-data")
// this could also fit a narrow use case
// document.querySelectorAll("input[type='hidden']")
Edit: added clarification to method 2
you can access model directly in razor page like #ModelName.objectname but you should import model like
#model ModelName
example : #Model.id
I have the following form posted on a wordpress page.
I´d like to catch users without referrers to set the referrer on their own (that referrer part is all handled by a plugin... does not matter here).
The registration form Url is like:
http://myurl.com/register/
The code below just works fine. Inserted directly into the wp page editor (text).
Except it creates a Url like follows:
http://myurl.com/register/?id=testinput
How do i get the resulting Url to be formatted this way?:
http://myurl.com/register/sp/testinput
<h3>Your ID</h3>
<p>Please input your ID</p>
<form id = "submit_id_form" onsubmit="myIDFunction()">
<input type="text" name="id">
<input type="submit" value="Confirm">
</form>
<?php
function myIDFunction(){
var action_src = "http://myurl.com/register/" + document.getElementsByName("id")[0].value;
var submit_id_form = document.getElementById('submit_id_form');
submit_id_form.action = action_src ;
} ?>
</script>
This is the original form code (reference below) i`m trying to modify:
<form id = "your_form" onsubmit="yourFunction()">
<input type="text" name="keywords">
<input type="submit" value="Search">
function yourFunction(){
var action_src = "http://localhost/test/" +
document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
</script>
I tried to append the /sp/ part and remove the appended question mark "?" in the code above.. but i´m totally stuck with coding. (I´m a "clicker" not a coder so to speak)
Thank you very much guys and gals :)
Original Code is from here
You have to return true from method called on onsubmit as
function yourFunction(){
var action_src = "http://localhost/test/" + document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
return true;
}
I have this text box here...
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
and I also have this submit
<input type="submit" name="btnSearch" value="Search" onclick="location.href='http://www.website.com/search/';" id="btnSearch" class="buttonSearch" />
what I am trying to do is add whatever is in the text box in my
onclick="location.href='http://www.website.com/search/';"
so it would look like this..
onclick="location.href='http://www.website.com/search/what ever the user searches';"
how would I go about doing this, I have been googling my little heart out.
Please avoid mixing JavaScript and HTML. You can remove onclick attribute and replace it with this in plain JavaScript somewhere after the DOM has loaded:
document.getElementById('btnSearch').onclick = function() {
var search = document.getElementById('search').value;
var searchEncoded = encodeURIComponent(search);
window.location.url = "http://www.website.com/search/" + searchEncoded;
}
Also remember about escaping the search box, e.g. using encodeURIComponent(). Here is a working jsfiddle example.
This should work:
onclick="location.href='http://www.website.com/search/'+document.getElementById('search').value;"
But I wouldn't ever write that in one of my project as writing script directly on tags is a bad practice.
Here is a working jsfiddle
I moved the event handler out of the button as it is more maintainable. Also I encode the search query so that it gets to the server properly.
var search = document.getElementById('search');
var submit = document.getElementById('btnSearch');
submit.addEventListener('click', function(e) {
var searchValue = encodeURIComponent(search.value); // encode the search query
window.location.href = 'http://www.website.com/search/' + searchValue ;
});
You can add it to the onclick event like so
document.getEelementById("btnSearch").onclick = function(){
location.href='http://www.website.com/search/' + document.getEelementById("search").value;
}
edit: aaaaand too slow... oh well. At least this is not inline.
You would be better off using the < script> tag for this task. Example:
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
...
<input type="submit" name="btnSearch" value="Search" id="btnSearch" class="buttonSearch" />
<script type="text/javascript">
var button= document.getElementById('btnSearch');
button.onclick= function(){
var text= document.getElementById('search').value;
location.href='http://www.website.com/search/'+text;
}
</script>
However, you should try to 'clean' a little the text from the textbox so when you append it to the url you get a valid url. You should trim the text, then search for special characters and escape them, etc.
This is a follow up to my other question. I am asking again because this seems more a javascript question than a Google App Engine question.
I have a form
<form name="choice_form" id="choice_form" method="post" action="/g/choicehandler" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
I want to take the value of this textarea and send it to the app with formData. I tried this
var choice = document.getElementById("choice_form").value;
but I get "undefined" for the value of "choice". What am I doing wrong?
And also, if I understand correctly, the /g/choicehandler is called twice once by the form and once by the XHR. How do I fix that? Below is the handler:
class Choice(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<head>
<script type="text/javascript">
var count = 0;
function writeToStorage()
{
var user = "user" + count;
count++;
localStorage.setItem("chooser", user);
var choice = document.getElementById("choice_form").value;
var formData = new FormData();
formData.append("chooser", user);
formData.append("choice", choice);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8086/g/choicehandler", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4 && xhr.status == 200){
console.log("request 200-OK");
}
else {
console.log("connection error");
}
};
xhr.send(formData);
//added this per Aaron Dufour's answer
return 0;
};
</script>
</head>
<body>
//changed onsubmit like this: onsubmit="return writeToStorage(); as per Aaron Dufour's answer
<form name="choice_form" id="choice_form" action="/g/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
</body>
</html>""")
UPDATE
See Aaron Dufour's answer for the solution.
choice_form is the <form>, not the <textarea>.
You need to give the <textarea> an ID and use that ID instead.
You can access the form formally using:
document.forms['choice_form']
or also:
document.forms.choice_form
Each form has an elements collection that is all the form controls. You can access them much the same way:
document.forms['choice_form'].elements['choice']
or
document.choice_form.choice
provided the names follow the rules for valid javascript identifiers. If they don't, you need to use square bracket notation:
document['choice_form']['choice']
all return a reference to the element named 'choice' in a form with name 'choice_form'. So to get the value:
document.choice_form.choice.value
(Some great answers here, but I haven’t seen one that puts it together with what you have…)
Since a form can have more than one input, you need to access value on a particular one. There are a few ways to do this, but the most straightforward might be to use the form’s elements property (only forms have this!):
document.getElementById("choice_form").elements.choice.value
As others have said, you're accessing the form, when the data you want is in the textarea. If you give the textarea an ID, that's probably the easiest way to get to its value.
After much discussion, we determined that you don't need XHR at all. Here's what your form should look like:
<form name="choice_form" id="choice_form" action="/g/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="hidden" name="chooser" id="form_chooser" />
<input type="submit" value="submit your choice">
</form>
And now, we use the javascript function to edit the form before allowing it to be submitted:
var count = 0;
function writeToStorage()
{
var user = "user" + count;
count++;
localStorage.setItem("chooser", user);
document.getElementById("form_chooser").value = user;
};
I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.