I have a small JavaScript issue.
I have the following form:
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
What I'm trying to do is to get the value from the select tag and use it in page2.
For example, is option is A, the value should be ="a".
I want to use the value="a" in page2.
document.getElementById("output"): here i want to print the result in page2.
What I've tried to do in the second page:
<script>
var select = document.getElementById("activity");
var e = select.options[select.SelectedIndex].value;
document.getElementById("output").innerHTML = e;
<!-- This doesn't show anything. -->
var test = document.getElementsbyName("activity").values;
document.getElementById("output").innerHTML = test;
<!-- The output is: function values() { [native code] } -->
var test = document.getElementsByName("activity").value;
document.getElementById("opinion").innerHTML = test;
<!-- The output is: undefined -->
</script>
So basically, getting the select element by ID or by Name doesn't work.
Getting the select element ID.value doesn't work.
Getting the select element by the index doesn't work.
Any ideas? I've literally tried anything.
Am I writing the code in the wrong place?
Do I have to send this information through the server-side?
P.S.: I am writing the app in Node.js and Express and I'm using handlebars.
Kind regards,
G.
Update:
If you want to get the value to other page, you need to fetch it from url as whole new page get rendered and your old values will not exist exist.
If you are having your values in url just fetch it by this
let url = window.location
I assume, you are trying to get the value of dropdown
select has always the value attribute to it which actually is the value you select from dropdown
You just need to look for the value of select whenever you want the selected option.
Here in your case just attach a onchange listener to select, which triggers whenever the value of select get changed
var select = document.getElementById("activity");
var mySelectValue = select.value // set the default value
select.onchange = function() {
console.log(select.value)
mySelectValue = select.value // update whenever value get changed or new value chosen
}
// Do whatever you want to do with selectvalue
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
So basically, I have fetched the link and I tried to check if the activity = something.
example down below:
if(url.href.indexOf("activity=a") > -1){
activity = "a"
}
document.getElementById("opinion").innerHTML = activity;
Of course, in the page2, I can see "a" as a result which is great! :)
Related
I'm trying to create a cookie to store a value from a select form field - I'v been trying different options but unsuccessful everytime 😥 - can someone please help me?
The site is currently on Drupal but I'm wanting to add via Tag Manager, so any help with vanilla JS would be amazing
The Hubspot form in question can be located: https://www.huddle.com/get-started
The select field is : Comapany Size
The value I'm trying to target is the first option: 1-10
This is my code:
<script>
var formField = document.querySelector('form["name="size_of_organisation__c"]').value;
var formValue = "1-10";
var cookieName = sizeOfOrg;
var cookieValue = smb;
if (formField == formValue) {
document.cookie = "cookieName=cookieValue";
}
</script>
Any help would be much appreciated
Humm,
it seems you are using react, so it will be definitely nice to create this process in a react fonction inside your form component, etc.
I'm not really sure of your needs, but this code retrieve the value of the dropdown on change and add it in a cookie :
<html>
<body>
<form>
<select name="size_of_organisation__c">
<option value="" disabled="" selected="">Please Select</option>
<option value="1-10">1-10</option>
<option value="11-50">11-50</option>
<option value="51-200">51-200</option>
<option value="201-500">201-500</option>
<option value="501-1000">501-1000</option>
<option value="1001-5000">1001-5000</option>
<option value="5001-10000">5001-10000</option>
<option value="10001+">10001+</option>
</select>
</form>
</body>
<script src="./temp.js"></script>
</html>
//selector to select dropdown. return an array so take the first one
var select = document.getElementsByName("size_of_organisation__c")[0];
console.log(select);
// add event handler to update the cookie each time you change the select
select.addEventListener("change", function() {
document.cookie = "sizeOfOrg=" + select.value;
console.log(document.cookie);
});
edit: add the html and the console.log() to debug
Self teaching Node.js and Javascript stuff. I have in the form in my HTML and select, drop down menu option. How do I get the index of the selected value?
So far im trying this:
var e = req.body.boolean_choice;
boolChoice = e.selectedIndex;
I have the req.body working for getting the inputted values in a text box, but it tells me selectedIndex is not a thing. So then I tried:
var e = req.body.boolean_choice
to see what that gave and it just gave undefined.
Is there a way to do this?
Here is the HTML:
<form action="http://localhost:3000" method="POST">
Form:<br>
<br>
<br>
Text Box 1: <input type="text" name="tb1" size="35" placeholder=""#10SadioMane" OR "#Mane"">
<br>
<br>
<select id="choice" name="choice">
<option value="OR">OR</option>
<option value="AND">AND</option>
</select>
<br>
<br>
<input type="submit" value="Submit">
Form submitting will pass only value property of selection.
Also use debugger in IDE that you use, to explore req.body, instead of trying to guess what's there.
Happy to help.
First of all get the Selected option DOM element
var el = document.querySelector('#choice option:selected');
ibn your case it will be
req.body.querySelector('#choice option:selected');
Now logic is to iterate to the previous siblings in the chain till you reach to the top.
var index = 0;
while( el.previousSibling ! == null){
el = el.previousSibling;
index +=1;
}
console.log(index);
I have these 2 drop downs:
I have to provide values of Select Item drop down based on the value chosen in the Select Category drop down.
This is my PHP for Select Category drop down:
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onclick="document.form.submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
But nothing is happening. How do I do it?
Try onchange instead of onclick
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onchange="document.forms[0].submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
Two more things you should notice
onchange="document.form.submit();" this will not work because
document doesn't have a property form it is forms so you should
use onchange="document.forms[0].submit();"
You have named your submit button as submit which will prevent the
form from submitting because submit is a javascript function so
rename your submit button to something else.
If you dont have many possible values for your dropdowns, you can use plain old javascript for that purpose. See this http://jsfiddle.net/mplungjan/65Q9L/, but it requires all values to be loaded at once on the page load like this:
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
document.form.submit(); will submit the form which is not the requirement.
Instead you need to make an ajax call with the selected value from first dropdown and the response will be use to build the options of second dropdown.
use change which will trigger on change of option
$('category').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value; // will give value of selected option
$.ajax({
url:"someUrl", // this url will return response from backend
// other methods
success:function(response){
//use this response to build the second dropdown
}
})
});
I load some hidden data into a datalist and bind it with the data attribute.
If a value selected, I want to get the value of the corresponding data attribute. This is my code:
<input list="browser" id="number">
<datalist id="browser">
<option data-customValue="Abc" value="Firefox">1</option>
<option data-customValue="Def" value="Chrome">2</option>
<option data-customValue="Ghi" value="Explorer">3</option>
</datalist>
$('#number').on('input', function() {
var value = $('#browser').val();
alert($('#browsers [value="' + value + '"]').data('customValue'));
});
In my case, I only get undefined as a response.
Here is the fiddle: https://jsfiddle.net/bd4rpztk/1/
There's two issues in your code. Firstly you need to get the val() from the input element, not the datalist. Secondly data attribute names should be lowercase otherwise it interferes with jQuery's internal cache. With that in mind, try this:
<input list="browser" id="number">
<datalist id="browser">
<option data-customvalue="Abc" value="Firefox">1</option>
<option data-customvalue="Def" value="Chrome">2</option>
<option data-customvalue="Ghi" value="Explorer">3</option>
</datalist>
$('#number').on('input', function() {
var value = $(this).val();
alert($('#browser [value="' + value + '"]').data('customvalue'));
});
Working example
Note that your logic may need to be amended to cater for people who are typing a value directly in to the input.
I have an html form that uses select and text inputs. The form comes pre-populated with default values. How can I submit only the inputs that were changed by the user from their default values? Note that this page is to be stored in an embedded system with limited space, so using a javascript library is out of the question.
Example html:
<form>
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
<select name="field3">
<option value="option1" select>Option 1</option>
<option value="option2" select>Option 2</option>
</select>
<input type="Submit" />
</form>
To be clear, inputs that the user does not change should not show up in the POST request when the form is submitted.
As per Barmar's suggestion to use an array to track which values have changed, this is the solution I have come up with and it works.
Here is the js:
var tosubmit = []
function add(name) {
if(tosubmit.indexOf(name) == -1)
tosubmit.push(name);
}
function is_changed(name) {
for(var k = 0; k < tosubmit.length; k++)
if(name == tosubmit[k])
return name && true;
return false;
}
function before_submit() {
var allInputs = document.getElementsByTagName("input");
var allSelects = document.getElementsByTagName("select");
for(var k = 0; k < allInputs.length; k++) {
var name = allInputs[k].name;
if(!is_changed(name))
allInputs[k].disabled = true;
}
for(var k = 0; k < allSelects.length; k++) {
var name = allSelects[k].name;
if(!is_changed(name))
allSelects[k].disabled = true;
}
}
html:
<form onSubmit="beforeSubmit()">
<input type="text" name="field1" value="value1" onchange="add('field1')" />
<input type="text" name="field2" value="value2" onchange="add('field2')" />
<select name="field3" onchange="add('field3')">
<option value="option1" select>Option 1</option>
<option value="option2" select>Option 2</option>
</select>
<input type="Submit" />
</form>
This works because form elements that are disabled are not included in the POST Request. Thanks everyone for their suggestions.
If you can use HTML5, you can use the placeholder attribute, example. Keep in mind this won't work with older browsers like IE6-8.
<form>
<input type="text" placeholder="placeholder text" name="field1" value="" />
<input type="Submit" />
</form>
If you can't use that, you'll have to do a detect on form submit with javascript and check the value of the objects your submitting. The other option is to have a label of your preview text and hide it when input boxes are selected or contain a value that isn't empty.
waldol1's method works. Here I'm making a suggestion, and offering an alternate way.
Improvement:
For cleaner code, just use "add(this)" for each input element.
<input onchange="add(this)" />
Then, in the add() function, just add one more line to get the name of the element being clicked
function add(e) {
var name = e.name;
// do stuff
}
Alternate solution:
I'm not submitting a form the classic way; I'm just using input elements and doing stuff with Javascript. I don't care about disabling form elements, and don't want to rely on that as a flag. Instead I'm using a JS object to store my changed variables, then I just run through the object when I build my parameters (in my case, to submit via AJAX request).
Define a global "tosubmit" object (you could use an array if you want).
var tosubmit = new Object();
For any input element I want updateable, I call add(this) when there's a change:
<input onchange="add(this)" />
The JS function adds the changed element to my temporary storage object.
function add(e) {
// Store the element and it's value, ready for use later.
tosubmit[e.name] = e.value;
}
When I'm ready, I build parameters for my AJAX update. In my casI run the function with an ID, in my case. I run through the tosubmit object, and if the update is successful, I clear it out, ready for another use.
function sendUpdate(id) {
// Start building up my parameters to submit via AJAX to server.
var params = "id="+encodeURIComponent(id);
// Run through the tosubmit object, add any updated form elements.
for (var i in tosubmit) {
params = params + "&" + i + "=" + encodeURIComponent(tosubmit[i]);
}
// (Do other stuff, build my http request, etc)
// Eventually submit params with the http request
http.send(params);
}