I am creating an HTML page which will accept user inputs and queries a database at the backend. To start off I am just trying to take user's output and display how the query will look like on the same page.
It has two radio buttons.
I am able to display the user selections, but right now its shows text for all buttons instead of the radio button selection. How can I restrict the display of text based only on the radio button which is selected? Here is my code -
<form id="data" method="post">
<input type="radio" id="Name" > Name
<input type = "text" id="value1"> <br>
<input type="radio" id="Last"> Lastname
<input type = "text" id="value2"> <br>
<input type="submit" onclick="return query()" value="Get Total">
<p style="font-size:80%;"> <span id='boldStuff1'> </span> <br> <span id='boldStuff2' > </span> </p>
</form>
<div id="display" style="height: 50px; width: 100%;"></div>
function query(){
var a = document.forms["data"]["value1"].value;
var b = document.forms["data"]["value2"].value;
var display=document.getElementById("display")
document.getElementById('boldStuff1').innerHTML= " SELECT * FROM table WHERE Name = " + a ;
document.getElementById('boldStuff2').innerHTML= " SELECT * FROM table WHERE Last = " + b ;
return false;
}
Here is how query looks like right now -
http://jsfiddle.net/mw6FB/104/
Thanks!
This will work,
function query(){
//var a = document.forms["data"]["value1"].value;
//var b = document.forms["data"]["value2"].value;
//var display=document.getElementById("display")
//document.getElementById('boldStuff1').innerHTML= " SELECT * FROM table WHERE Name = " + a ;
//document.getElementById('boldStuff2').innerHTML= " SELECT * FROM table WHERE Last = " + b ;
var nameDisplay = document.getElementById('boldStuff1');
var lastNameDisplay = document.getElementById('boldStuff2');
if(document.getElementById('Name').checked) {
var a = document.forms["data"]["value1"].value;
nameDisplay.innerHTML= " SELECT * FROM table WHERE Name = '" + a + "'";
lastNameDisplay.innerHTML= "";
} else if(document.getElementById('Last').checked) {
var b = document.forms["data"]["value2"].value;
lastNameDisplay.innerHTML= " SELECT * FROM table WHERE Last = '" + b + "'";
nameDisplay.innerHTML= "";
}
return false;
}
<form id="data" method="post">
<input type="radio" id="Name" name="radioQuery" checked > Name
<input type = "text" id="value1"> <br>
<input type="radio" id="Last" name="radioQuery"> Lastname
<input type = "text" id="value2"> <br>
<input type="submit" onclick="return query()" value="Get Total">
<p style="font-size:80%;"> <span id='boldStuff1'> </span> <br> <span id='boldStuff2' > </span> </p>
</form>
<div id="display" style="height: 50px; width: 100%;"></div>
You're not doing anything with the radio buttons. Find out which one is selected (if any), and only assign the innerHtml of the selected one. You may want to clear the other one as well. You can do this with a simple if().
See for example How to get value of selected radio button?.
Also, if you want to be able to actually submit this form and read its values, you'll want to name your input elements.
Related
This program has 6 text fields and when a user inputs into the text fields, the text result box will concatenate the input text. I am struggling to get a button to work which will add a 7th text field and then also add the user input together. I have tried to append it but not sure where I am going wrong.
<html>
<body>
<form>
<div class="textFields">
<label for="text1">text1:</label><br>
<input type="text" class="text" name="text1"><br>
<label for="text2">text2:</label><br>
<input type="text" class="text" name="text2"><br>
<label for="text3">text3:</label><br>
<input type="text" class="text" name="text3"><br>
<label for="text4">text4:</label><br>
<input type="text" class="text" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" class="text" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" class="text" name="text6"><br>
<input type="button" name="button" value="Get"><br>
<input type="button" name="button" value="Add">
<br>
<label for="textResult">Text Result</label><br>
<input type="text" id="textResult" name="textResult"><br>
</div>
</form>
<script>
let x = document.querySelectorAll('.textFields .text');
let button = document.querySelector('.textFields input[type="button"]');
let result = document.querySelector('#textResult');
button.onclick = function() {
result.value = '';
for (i = 0; i < x.length; i++) {
result.value += x[i].value + ' ';
}
}
button.onclick = function() {
var textField = document.createElement("INPUT")
textField.setAttribute("id", id)
textField.setAttribute("name", id)
textField.classList.add("textInput")
container.appendChild(textField)
}
</script>
</body>
</html>
When you run this in a browser, the following error is reported in the console when you click the Get button:
Uncaught ReferenceError: id is not defined
at HTMLInputElement.button.onclick (test.html:53)
Ignore the error for now, you can see that the error in actually in the second function, but for Get you were probably expecting the first funtion. To fix this issue, do not assign the second function, at least not to the button you have selected.
Notice how you have named both buttons the same name, this will make them hard to target, but also you are not using that name in the querySelector. So lets change that first, give each button a unique name and use it to select each button:
<input type="button" name="getButton" value="Get"><br>
<input type="button" name="addButton" value="Add">
let getButton = document.querySelector('.textFields input[name="getButton"]');
let addButton = document.querySelector('.textFields input[name="addButton"]');
...
getButton.onclick = ...
...
addButton.onclick = ...
Now, when you click on the Get button there is no error, and it appears to function as you have described, clicking Add still raises the original error.
You have used a variable called id but you have not yet declared what that variable is yet. I would assume you probably want to make it 'textX' where x is the next number.
So add the following lines inside the button click function to declare the Id:
You need to put this logic inside the function because you need it to be re-evaluated each time the button is clicked. Other valid solutions would include incrementing the value instead or re-querying for x, but this will work.
let x = document.querySelectorAll('.textFields .text');
let id = 'text' + (x.length + 1);
Save and Run, you will see the next issue in the console:
Uncaught ReferenceError: container is not defined
at HTMLInputElement.addButton.onclick
As with id, you have not defined the variable container, here I will again assume you meant to reference the .textFields div, so following your querySelector style, we can create a variable called container:
let container = document.querySelector('.textFields');
That will start appending your text boxes to the page, but they are still not being picked up by the Get button.
Another assumption here, but you have assigned a class .textResult to the new texboxes. If instead you assigned the class .text to them, then you would almost pick them up in the selector
textField.classList.add("text");
The reason that they aren't picked up is back to where the value of x is evaluated that the Get button is using. Because it is evaluated the first time in the main script, but never re-evaluated when the button is clicked the new text boxes are not included in the array stored in x.
As with the advice above for requerying x to get the updated count, Simply fix this by moving the line to initialise x into the first function.
Overall, your page with the embedded script could not look something like this:
<html>
<body>
<form>
<div class="textFields">
<label for="text1">text1:</label><br>
<input type="text" class="text" name="text1"><br>
<label for="text2">text2:</label><br>
<input type="text" class="text" name="text2"><br>
<label for="text3">text3:</label><br>
<input type="text" class="text" name="text3"><br>
<label for="text4">text4:</label><br>
<input type="text" class="text" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" class="text" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" class="text" name="text6"><br>
<input type="button" name="getButton" value="Get"><br>
<input type="button" name="addButton" value="Add">
<br>
<label for="textResult">Text Result</label><br>
<input type="text" id="textResult" name="textResult"><br>
</div>
</form>
<script>
let getButton = document.querySelector('.textFields input[name="getButton"]');
let addButton = document.querySelector('.textFields input[name="addButton"]');
let result = document.querySelector('#textResult');
let container = document.querySelector('.textFields');
getButton.onclick = function() {
let x = document.querySelectorAll('.textFields .text');
result.value = '';
for (i = 0; i < x.length; i++) {
result.value += x[i].value + ' ';
}
}
addButton.onclick = function() {
let x = document.querySelectorAll('.textFields .text');
var textField = document.createElement("INPUT")
let id = 'text' + (x.length + 1);
textField.setAttribute("id", id)
textField.setAttribute("name", id)
textField.classList.add("text")
container.appendChild(textField)
}
</script>
</body>
</html>
Have a look at some of the guidance in this post for further simple examples: How do I add textboxes dynamically in Javascript?
Help me create checkboxes with embedded links
Everything
<body style="text-align: left;">
<h1>Select which delimiter you want to use.</h1>
<big>Select either TSV or CSV: </big><br>
<input type="checkbox" name="acs" value="CSV">CSV<br>
<input type="checkbox" name="acs" value="TSV">TSV<br>
<p>
<input type="button" onclick='printChecked()' value="Print Selected Items" /input>
</p>
</body>
It prints checkboxes with no attached links.
Following code contains what you are looking for
function printChecked(){
var checkboxes = document.getElementsByName("acs");
var list = document.getElementById("chckValues");
list.innerHTML = "";
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked == true){
var listentry = document.createElement('li');
var link = document.createElement('a');
link.href = '#' + checkboxes[i].id
link.appendChild(document.createTextNode(checkboxes[i].value));
listentry.appendChild(link);
list.appendChild(listentry);
}
}
}
<h1>Select which delimiter you want to use.</h1>
<big>Select either TSV or CSV: </big><br>
<input type="checkbox" id="acs1" name="acs" value="CSV">CSV<br>
<input type="checkbox" id="acs2" name="acs" value="TSV">TSV<br>
<p>
<input type="button" onclick='printChecked()' value="Print Selected Items" /input>
</p>
<ol id="chckValues"></ol>
I have a dynamic section in my html form. When clicking on a button, user can add a tag name and tag type. At a point, imagine that there are 3 set of tag names and tag types, the data should be submitted in the following format.
Array[0][name] = tag1 name, Array[0][type] = tag1 type
Array[1][name] = tag2 name, Array[1][type] = tag2 type
Array[2][name] = tag3 name, Array[2][type] = tag3 type
Can someone help me on this ?
I think you are looking to have a multidimensional array that can store an array within each position of the array. Assuming you have already a form, html should look something like this:
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>
For the functionality, you could have something like this to store the information and then submit the form:
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
You can check in the console in the developer tools for the information you are about to submit.
Let me know if this helps,
Leo.
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>
here is another possibility for how to make this work. a simple form with a div to contain the tags and a small input field to add a new tag.
var tagid = 1;
function addTag() {
var div = document.getElementById("tags");
var name = document.getElementById("tname").value;
var type = document.getElementById("ttype").value;
div.innerHTML += "tag" + tagid + "<br><input type='text' name='tag[" + tagid + "][name]' value='" + name + "'><br><input type='text' name='tag[" + tagid + "][type]' value='" + type + "'><hr>";
tagid++;
}
<html>
<body>
<form id="form">
tags:<br>
<div id="tags">
</div>
<input type="submit" value="Submit">
</form>
<hr> tag name: <input id="tname" type="text" name="tname"><br> tag type: <input id="ttype" type="text" name="ttype"><br>
<button onclick="addTag()">add tag</button>
</body>
</html>
i am making a database programm where the user has to submit some of his contact information.
<form action="add_action.php" method="POST">
<div class="modal-body">
Name: <br>
<input type="text" name="name" placeholder="Name" required><br>
Telefon Nr. <br>
<input type="text" name="telNr" placeholder="Telefon Nr."><br>
Handy Nr. <br>
<input type="text" name="handyNr" placeholder="Handy Nr."><br>
Skype ID <br>
<input type="text" name="skypeId" placeholder="Skype ID"><br>
<div class="modal-footer">
<input type="submit" class="btn btn-default" value="Hinzufügen">
</div>
</form>
i have been researching a while now, but i cant seem to figure out how i can set the form so at least 1 out of "Telefon Nr.", "Handy Nr." and "Skype ID" is required. if you have any sugestions of what i should do i would apreciate your input.
Consider reading this. I'll be showing, only, how to check for the presence of the field named name alongside at least one field from the others.
Sever side verification:
Ps: you didn't give the submit button a name, i'll give it a name="submit", for example, to make checking for form submission possible within php.
if{isset($_POST["submit"])
// don't rely on HTML required attribute, a user with a bit of knowledge can remove/bypass it, I mean check for the presence of the name either
$name = trim($_POST["name"]);
$telNr = trim($_POST["telNr"]);
$handyNr = trim($_POST["handyNr"]);
$skypeId = trim($_POST["skypeId"]);
if(isset($name[0]) && (isset($telNr[0]) || isset($handyNr[0]) || isset($skypeId[0]))) {
echo "At least one field is present alongside with the name";
} else {
echo "The name and/or the other fields are empty";
}
}
Client side verification:
Ps: let me give an ID to the form tag, let's say id="my-form".
var myForm = document.getElementById("my-form");
myForm.addEventListener("submit", function(event){
// get all the fields values, and trim them on the fly
var name = document.getElementsByName("name")[0].value().trim(),
telNr = document.getElementsByName("telNr")[0].value().trim(),
handyNr = document.getElementsByName("handyNr")[0].value().trim(),
skypeId = document.getElementsByName("skypeId")[0].value().trim();
// we want the name and at least one other field to be filled
if(name !== "" && (telNr !== "" || handyNr !== "" || skypeId !== "" )) {
alert("we're good to go, the name is provided alongside with at least another field");
} else {
event.preventDefault(); // we cancel form submission as the name and/or the other fields are empty using the Event argument
alert("Cancelled, please fill in the name and at least one other field");
}
});
Hope I pushed you further to more understand how things work
Ps: that's a really basic example, don't rely on this in production phase as the code I provided may be vulnerable to some attacks(such as XSS aka Cross-Site-Scripting, SQL injection...).
You'd need to use some javascript to do this. The only thing you can do with HTML is add the "required" attribute as you've done with the name already.
This is the way i created it in a form i made a while back. I have edited it for you so place it in and should work off the bat.
<script>
function validateForm() {
var a,b,c,d = document.forms["form"]["name","telNr","handyNr","skypeId"].value;
if (a,b,c,d==null || a,b,c,d=="")
{
alert("Please complete all Required Fields *");
return false;
}
}
</script>
<body>
<form name="form" action="add_action.php" onsubmit="return validateForm()" method="POST">
<div class="modal-body">
Name: <br>
<input type="text" name="name" placeholder="Name"><br>
Telefon Nr. <br>
<input type="text" name="telNr" placeholder="Telefon Nr."><br>
Handy Nr. <br>
<input type="text" name="handyNr" placeholder="Handy Nr."><br>
Skype ID <br>
<input type="text" name="skypeId" placeholder="Skype ID"><br>
<div class="modal-footer">
<button type="submit" class="btn btn-default" value="Hinzufügen" >Sign In</button>
</div>
</form>
I have this HTML form which works fine when written like this:
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
</fieldset>
But when I change 3rd and 4th line to:
<input type="text" name="firstname" id="firstname" onblur="validateName(firstname)" />
<span id="firstnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
, onblur doesn't work! How could it be? After all i just changed the name and ID?
This is my validateName(name) function:
function validateName(x) {
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if (re.test(document.getElementById(x).value)) {
// Style green
document.getElementById(x).style.background = '#ccffcc';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
} else {
// Style red
document.getElementById(x).style.background = '#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
thanks
You need to change ID of error element too (because of x + Error).
<span id="firstnameError"...>
And put function params into quotes:
<input type="text" name="firstname" id="firstname" onblur="validateName('firstname')" />
http://jsfiddle.net/Lgp55uwo/