Can't get Result to show with HTML Forms and Javascript - javascript

I'm trying to get my results to show up in the text box inputs as per my assignment but I can't get them to show up at all. The math isn't showing up at all so my big issue is that I can't get the code to show up in the box.
document.querySelector.("#buttonS").addEventListener("click", function(e) {
if (document.querySelector("#gallons").reportValidity()) {
let gallons = document.querySelector("#gallons").value;
if (document.querySelector("#quarts").checked) {
quartsTotal = gallons * 4;
document.querySelector("#quartsResult").placeholder = `quartsTotal`);
} else if (document.querySelector("#pints").checked) {
} else if (document.querySelector("#cups").checked) {
}
}
});
<form id="bakimg">
<input type="number" step=".01" min="0" id="gallons" required><label for="gallons"> How many gallons of milk do you have?</label>
<br>
<br>
<label for="conversion">Which conversion would you like?</label><br>
<input type="radio" value="quarts" name="gallonsC" checked><label for="quarts">Quarts</label>
<input type="radio" value="pints" name="gallonsC"><label for="pints">Pints</label>
<input type="radio" value="cups" name="gallonsC"><label for="cups">Cups</label>
</form>
<br>
<button type="button" id="buttonS">Submit</button><br>
<h1>Results</h1>
<br>
<input type="text" id="quartsResult" placeholder=""><label for="quartsResult">Quarts</label><br>
<input type="text" id="pintsResult"><label for="pintsResult">Pints</label><br>
<input type="text" id="cupsResult"><label for="cupsResult">Cups</label>
</div>

Check your syntax and make the following changes:
Check the browser console for errors and use the appropriate syntax:
document.querySelector.("#buttonS")
should be written like this:
document.querySelector("#buttonS") // No . after querySelector
Check the extra parentheses:
document.querySelector("#quartsResult").placeholder = `quartsTotal`); // <-- Remove the closing parens
Add the proper IDs to the HTML input elements (quarts, pints, cups):
<input type="radio" value="quarts" name="gallonsC" checked id="quarts">
<input type="radio" value="pints" name="gallonsC" id="pints">
<input type="radio" value="cups" name="gallonsC" id="cups">
Remove the backticks in order to use the variable value (otherwise quartsTotal is still a string):
`quartsTotal` -> quartsTotal
// Perhaps this is what you meant:
`${quartsTotal}`
Good luck with the assignment!

Related

why isn't 2nd IF statement read?

The second if statement is not reached/read.
I switched order of the two if statements; only the first produces a result. I put semicolons various places, but now I understand they are optional. I removed the line space.
function myChoices() {
if (document.getElementById("state").checked)
{document.write("state")}
else if (document.getElementById("county").checked)
{document.write("county")}
else {document.write("country")}
if (document.getElementById("range30").checked)
{document.write("30yrs")}
else if (document.getElementById("range50").checked)
{document.write("50 yrs")}
else {document.write("100yrs")}
}
<input type="radio" name="region" id="state">State <br>
<input type="radio" name="region" id="county">county <br>
<input type="radio" name="region" id="country">country <br>
<br><br>
<input type="radio" name="timerange" id="range30">30 years<br>
<input type="radio" name="timerange" id="range50">50 years<br>
<input type="radio" name="timerange" id="range100">100 years<br>
<button onclick="myChoices()">my selections are made</button>
I select one choice from each set of radio buttons and click the button. Only the result from the first if is returned.
Why?
The problem is document.write. As a rule of thumb, never use document.write.
In your example, when the first if statement calls document.write, it wipes out the HTML document and replaces it by e.g. country.
Then if (document.getElementById("range30").checked) runs, but document.getElementById("range30") doesn't find any element with id range30 because the whole page has been wiped out and replaced by country, so it returns null. Trying to access null.checked throws an exception, which aborts execution of the function.
If you really want to use document.write (which I don't recommend), only call it once, at the end of your function:
function myChoices() {
var text = "";
if (document.getElementById("state").checked) {
text += "state";
} else if (document.getElementById("county").checked) {
text += "county";
} else {
text += "country";
}
if (document.getElementById("range30").checked) {
text += "30yrs";
} else if (document.getElementById("range50").checked) {
text += "50 yrs";
} else {
text += "100yrs";
}
document.write(text);
}
<input type="radio" name="region" id="state">State <br>
<input type="radio" name="region" id="county">county <br>
<input type="radio" name="region" id="country">country <br>
<br><br>
<input type="radio" name="timerange" id="range30">30 years<br>
<input type="radio" name="timerange" id="range50">50 years<br>
<input type="radio" name="timerange" id="range100">100 years<br>
<button onclick="myChoices()">my selections are made</button>
In addition to the above to responses, it is not a good idea to use document.write in callback as it will replace the document content when invoked after the document has loaded. If the document is still open then it will not replace the content.
It is always safer to use .appendChild() to add new DOM elements.
For your use case you can use .textContent to display the results.
function myChoices() {
var resBox = document.getElementById("result");
var selectedRegion = "";
var selectedTimerange = "";
if (document.getElementById("state").checked)
{selectedRegion ="state"}
else if (document.getElementById("county").checked)
{selectedRegion = "county"}
else {selectedRegion ="country"}
if (document.getElementById("range30").checked)
{selectedTimerange ="30yrs"}
else if (document.getElementById("range50").checked)
{selectedTimerange ="50yrs" }
else {selectedTimerange ="100yrs"}
resBox.textContent = `${selectedRegion} ${selectedTimerange}`
}
<input type="radio" name="region" id="state">State <br>
<input type="radio" name="region" id="county">county <br>
<input type="radio" name="region" id="country">country <br>
<br><br>
<input type="radio" name="timerange" id="range30">30 years<br>
<input type="radio" name="timerange" id="range50">50 years<br>
<input type="radio" name="timerange" id="range100">100 years<br>
<button onclick="myChoices()">my selections are made</button>
<p id="result"></p>
When you click on the submit button, you will call the myChoices() function.
When it will first see a document.write, it will replace the whole HTML markup with your text in your input.
You can check the body of the result of your snippet:

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Changing onClick value through radio buttons

I am quite new to all this and wondering if someone can help with something. I have the code below which when the button is clicked is references a javascript file and populates a random english word. I am wanting to change it to add a radio button. The radio button will allow the user to select an english word or french word. How can I change my onClick command to use the value of the selected radio button?
<FORM NAME="Generator">
<INPUT TYPE=TEXT NAME="WordBox" id="wordbox"><BR>
<INPUT TYPE=BUTTON VALUE="Generate" onClick="English(document.WordForm);" id="button">
</FORM>
I guess that you've a function English that take the form as a only parameter, you don't have to change anything just add the radio and get the value from the form inside your function, like :
<FORM NAME="Generator">
<INPUT TYPE="TEXT" NAME="WordBox" id="wordbox">
<BR>
<INPUT TYPE="RADIO" NAME="language" value="ENGLISH">ENGLISH
<INPUT TYPE="RADIO" NAME="language" value="FRENCH">FRENCH
<BR>
<INPUT TYPE=BUTTON VALUE="Generate" onClick="English(document.WordForm);" id="button">
</FORM>
Then get the value :
function English(form){
var language = form.language.value;
}
Hope this helps.
I'm not sure if I fully understand what it is that you're trying to achieve, but is it something along the lines of what I've created in this fiddle?
https://jsfiddle.net/pq6eh1jk/5/
HTML:
<input id="word" type="text"/>
<input id="english" type="radio" name="language" checked="checked"> English
<input type="radio" name="language" value="english"> French
<input type="button" onclick="generateText()" value="Generate Text"/>
JS:
var englishWordBank = [ 'Animal', 'Bank', 'City' ];
var frenchWordBank = [ 'Avion', 'Bonjour', 'Chat' ];
var generateText = function() {
var wordInput = document.getElementById('word');
var randomIndex = Math.round(Math.random()*2); //Between 0-2
if (document.getElementById('english').checked)
wordInput.value = englishWordBank[randomIndex];
//French:
else
wordInput.value = frenchWordBank[randomIndex];
};

javascript - need little help to read multiple values by multiple buttons in single input

hello i need little help to read multiple values by multiple buttons like 1,2,3 and output in input like this 123 not only 1 number, concurnete number by every click
<input type="button" onclick="changeText(1)" value="1" >
<input type="button" onClick="changeText(2)" value="2">
<input type="button" onClick="changeText(3)" value="3">
<br>
<input type="text" id="count" value=""/>
function changeText(value) {
document.getElementById('count').value = value ;
}
floowed by next number
link demo
http://jsfiddle.net/J7m7m/541/
function changeText(value) {
document.getElementById('count').value += value ;
}

using innerHTML with <input>

I am trying to use the innerHTML method on an input tag and all i get back is a blank string. Here is the code i am useing.
javascript
function setName(ID){
document.getElementById('searchtitle').innerHTML = "Enter " + ID.innerHTML;
}
HTML
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)">Last Name</input><br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)">Phone Number</input><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
What is supposed to happen is depending on which radio button I pick the label for the input box should change. I can make the label.innerHTML=radio.value but the values are named for my php code and not formated nicely(ie. phonenumber vs. Phone Number) this is why I am trying to use the innerHTML of the radio button.
Any help I could get would be greatly appriciated.
you should embed input inside of label tag. input tag should closed by />. It's semantic HTML. When you do this clicking on label activate the input. InnerHTML only works for label then. It will return you label value.
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
</label>
JavaScript:
console.log(document.getElementById('searchtitle').innerHTML); // returns 'Enter Last Name'
If you want the value of an input tag, you want to use .value.
First, add labels around your inputs. Second, use getName(this.parentNode). Finally, call innerText instead of innerHtml.
<html>
<head>
<script>
function setName(el){
document.getElementById('searchtitle').innerHTML = "Enter " + el.innerText;
}
</script>
</head>
<body>
<label><input type="radio" name="searchtype" value="name" onclick="setName(this.parentNode)"/>Last
Name</label><br/>
<label><input type="radio" name="searchtype" value="phonenumber" onclick="setName(this.parentNode)"/>Phone
Number</label><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
</body>
</html>
Complete edit.
Ok, I figured out what you were looking for. First off, you've got to fix your HTML (don't put text inside of an input... and don't next an input inside of a label).
<label for="test">Last Name</label>
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)" />
<br/>
<label for="test2">Phone Number</label>
<input type="radio" id="test2" name="searchtype" value="phonenumber" onclick="setName(this)" />
<br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label>
<br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
JavaScript (in Jquery, for brevity):
function setName(elem)
{
$('#searchtitle').html('Enter ' + $('label[for="'+elem.id+'"]').html());
}
You have closed the Input tag improperly with </input>
this should be
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)"/>Last Name<br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)"/>Phone Number<br/>

Categories

Resources