Long story short:
I have a long list of check boxes for adding options to a purchase (TV, Radio, Stove, etc.)
Now I need to insert a LogIn form When they hit next (cut down on the number of quotes created/stored with no customer contact info).
But I was loosing all the options selected and would have to make the customer input again.
So I added an on-click - add to array function for the option id's selected. So that I could collect the ID's before submitting form.
Now the problem... How to send that array to the server with the php form, and I am way to new to Java.
In my research - I can either add the array values to the form action ?optionids=34,891,679,etc
Ugly but O.K.
What I would like is ... If this makes sense.. on-click of next button document.write
My code so far: (in )
<script type="text/javascript">
var numArray = [];
function addToArray(num){
numArray.push(num);
document.getElementById("pTxt").innerHTML = numArray;
return false;
}
</script>
<script>
function jstophp(){
var javavar=document.getElementById("pTxt").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar;?>";
}
</script>
I can see the values go in at
<div id="pTxt"></div>
But I can't pull them back out.
Any advice?
You should name your html inputs so that they become an array automatically in the $_POST
<input type="checkbox" name="options[tv]" value="tv">
<input type="checkbox" name="options[radio]" value="radio">
<input type="checkbox" name="options[stove]" value="stove">
Your $_POST will look something like:
options =>
tv => tv,
radio => radio
...
If that is not an option, use a hidden input element rather than a DIV to store your array:
<input type="hidden" id="pTxt" name="idList">
<script>
var numArray = [];
function addToArray(num){
numArray.push(num);
document.getElementById("pTxt").value = numArray;
return false;
}
</script>
Related
So basically I'm creating a program that allows the user to create and manage a ‘to-do list’. This will allow the user to add new items, remove selected items, highlight/un-highlight selected items, and sort the items, etc. I'm currently working on the add button, but I'm extremely confused with different functions in HTML and code that will allow me to manipulate the DOM.
When the user clicks the add button and the item name is valid, a new item should be added to the page’s to-do list (which esentially creates a new checkbox for every item the user adds). The checkbox is basically so the item can be selected/deselected, as well as the text that was in the item name textbox when the add button was clicked.
I guess I have two problems right now. I'm trying to verify that the item name is at least 1 character long. I wrote code in my "addHandler.js" file but when I write nothing in the textbox and click on the add button on my HTML browser, no error message pops up. I don't know why it's ignoring my function. Another thing I'm struggling with is the part that creates a new checkbox for every valid item that is added. I know how to create a checkbox on my HTML page, but I don't understand how to get my program to create a new one per item that the user inputs.
Any help or push in the right direction would be appreciated. I'm also new to HTML and javascript, so explaining stuff in simple terms would also make me really grateful.
todo.html code:
<html>
<head>
<title>Checklist</title>
</head>
<body>
<div><h1>My to-do list</h1></div><br />
<div id ="myCheckList">Enter an item:</div>
<div>Type something: <input type="text" id="textbox"></input></div>
<button type="button" id="addBut">Add item</button>
<button type="button" id="removeBut">Remove items</button>
<button type="button" id="toggleBut">Toggle highlight</button>
<button type="button" id="sortBut">Sort items</button>
<script src="addHandler.js"></script>
</body>
</html>
addHandler.js code:
function init(){
let button = document.getElementById("addBut");
button.onclick = buttonClicked;
let tb = document.getElementById("textbox");
tb.onblur = validate;
}
function add(){
let someEle = document.getElementById("myCheckList");
someEle.innerHTML = 'You added an item';
}
function validate(){
if(document.getElementById("textbox").value.length == 0){
alert("You need to enter something");
}
}
You should have a wrapper that contains your checkbox items that you can append new elements to.
<div id="checklist_items"></div>
Then you can use the following function to create a new div that contains a checkbox and the entered text, and then append it to your checklist:
function addItem() {
var input = document.getElementById("textbox");
var wrapper = document.getElementById("checklist_items");
if(input.value.trim() != "") {
var new_element = document.createElement("DIV");
new_element.innerHTML = '<input type="checkbox"> '+input.value;
wrapper.appendChild(new_element);
}
else {
alert("You must enter at least 1 character.");
}
}
I would also use the following to add the function to your button:
document.getElementById("addBut").addEventListener("click", addItem);
I have a page that loads a random MP3 file on each refresh. The user has to guess a name based on the sound via text form input. I want to check their input against the stored string and refresh the page if it's correct. Otherwise, I wan't to give them an incorrect alert and stay on the same page so they can guess again:
<div class="ui-widget" align="center">
<form method="post" action="" class="answer_box" onsubmit="return submit();">
<p>Which hero is it? <input id="tags" name="guess" /></p>
<script>
var key = <?php echo json_encode($rand_key) ?>;
var info = document.getElementById("guess").value;
function submit() {
if (key==info){
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
</form>
</div>
Right now, it submits the information to a new page regardless of the input. The javascript alerts are also not showing (I suspect they do show, but the page then refreshes and they disappear). The key variable is the key from the randomly taken value of a PHP array, and info should be the text the user inputs.
Problems found:
you cant use submit as a function name a this is an HtmlForm object
document.getElementById("guess").value; is looking for an element with ID of "guess" and that does not exist.
I would rewrite your script like this:
<script>
var key = <?php echo json_encode($rand_key) ?>;
function my_submit(curr) {
var info = curr.guess.value;
if (key == info) {
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
<form onsubmit="return my_submit(this);">
<p>Which hero is it? <input id="tags" name="guess"/></p>
</form>
You have a problem here:
<input id="tags" name="guess" />
Your id is tags, not guess.
You should use document.getElementById("tags").value.
You are trying to retrieve the value of an element with id of "guess." Change this to "tags."
var info = document.getElementById("tags").value;
Also, as #CodeGodie mentioned, you need to change your function name to something other than submit.
**Below is the input text fileds**
<form:form commandName="DRCNdetails" id="frm1" method="POST" action="addNewDelayReason.do" >
<form:input id="text1" path="delayCategory" cssClass="padR10 boxSizing" maxlength="75"></form:input>
<form:input path="preFix" id="text2" cssClass="padR10 boxSizing" maxlength="6"> </form:input>
<form:input path="reasonValue" maxlength="150" id="reasonValue" cssClass="textbox width100" cssStyle="visibility:hidden"></form:input>
</form:form> <button class="btnStyle blueBtn" onclick="formvalidation(),validateSpecialCharacters()"> <span class="left">
Submit
on submit need to vaidate the id's "text1","text2" fileds , on successful validation should display the below pop up screen that is showLtBox('mask', 'addMisdReasonCode1'), the conditions are below:
should not allow the null values for both the fileds, and special characters,and integers and alert me accordingly , on satisying this criteria only it should display the pop up screen showLtBox('mask', 'addMisdReasonCode1')
As far as I understand the question, you need to create a validation function that would be triggered upon pressing the submit button.
I already see that you have created to function that would be triggered on "OnClick" operation, However the syntax is incorrect.
You need to separate between the two function using ";" and not ","
You need to use only one function for validation - this would be more readable than the code you have written.
The result should be returned to the onclick command.
Example:
change the attribute onclick as follows:
onclick="return FullValidation();"
Create new JavaScript function that includes the two validations and return validation result;
function FullValidation() {
var validationResultOK = formvalidation();
if (validationResultOK) {
validationResultOK = validateSpecialCharacters();
}
if (validationResultOK) {
// Popup alert should be here, I put alert as example.
alert("Out your message here");
}
return validationResultOK;
}
Use Javascript Regular expression..
var pattern = new RegExp(/^[a-zA-Z]{n}$/);
where n is number of charecters you want to accept.
the above regular expression matches only charecters(both cases).
Now retrieve the value from your text fields
var text1 = document.getElementById("#your_id").value;
var text2 = document.getElementById("#your_id").value;
if(pattern.test(text1) && pattern.test(text2))
{
// your popup code
}
I've been having problems passing parameters from one .jsp to another.
I have two .jsp (1 and 2). In 1 I get some data from a database and show the user a bunch of checkboxes (depending on the data I got before). The user has to check one or more of the checkboxes, the selected will be deleted in my database in 2. (It´s something like "Select the numbers you want to delete").
I don't know how to pass the selected checkboxes and the value from 1 to 2.
I tried with javascript/jQuery, trying to know if a checkbox is checked and its value, add the value to a hidden field and use the request in 2 to get it.
1.jsp
<%
HttpSession sesion = request.getSession();
Company company = (Company) sesion.getAttribute("company");
List<Phone> phones = company.getTelefonos();
%>
<form id="formulario" method="POST" action="desMul_Final.jsp">
<fieldset>
<legend>Numbers</legend>
<%
Iterator<Phone> it1 = phones.iterator();
while(it1.hasNext()){
Phone t = it1.next();
String number = t.getNumero();
%>
<p>
<input name=check id="t_<%=number%>" type=checkbox value="<%=number%>" /> <%=number%>.
</p>
<%
}
%>
</fieldset>
<p class="buttons">
<button type=submit onclick="javascript: pick();">Continue</button>
</p>
</form>
Javascript/jQuery
function pick(){
var counter = 0;
$("#formulario fieldset p").each(function(index){
var field;
$(this).children("input").each(function() {
if($this.is(':checked')){
field = $(this).val();
}
});
index = index + 1;
texto = "<input type=hidden name=phone_"+index+" value="+field+" />";
$("#formulario").append(texto);
counter = index;
});
cant = "<input type=hidden name=amount id=amount value="+counter+" />";
$("#formulario").append(cant);
}
2.jsp (here I only try to know if I have the info)
<%
int amount = Integer.valueOf(request.getParameter("amount"));
System.out.println(amount);
for(int i = 1; i <= amount; i++){
String s = request.getParameter("phone_"+i);
System.out.println(s);
}
%>
When I try to access to request.getParameter("amount") I get an java.lang.NumberFormatException: null so I think my Javascript/jQuery is wrong.
How can I solve this?.
Are you familiar with debugging web application in a client-side way?
Can you please insert console.log("$("#formulario")) and then a breakpoint after $("#formulario").append(cant);, to see how the form's content changed, and if the hidden input was added ?
use int[] amount= Integer.ValueOf(request.getParameterValues("amount")); instead of request.getParameter("amount");
Well, I finally found the solution and I didn't need any Javascript. Searching in the API I found a method of the request called getParameterNames() that returns an Enumeration of String objects containing the names of the parameters contained in this request.
And I understood that when you submit the form, the checkbox value will be sent if the control is checked. Otherwise, nothing will be sent. So with this information and the method, I changed the way the checkboxes were constructed and use the enumeration to get the values.
BEFORE
<input name=check id="t_<%=number%>" type=checkbox value="<%=number%>" /> <%=number%>.
NOW
<input name="<%=number%>" type=checkbox /> <%=number%>.
So in my second .jsp I get a Enumeration with the names of the selected checkboxes, which are the phone numbers.
java.util.Enumeration enu = request.getParameterNames();
java.util.List<String> numbers = new java.util.ArrayList<String>();
while(enu.hasMoreElements()){
String s = (String)(enu.nextElement());
System.out.println(s);
numbers.add(s);
}
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.