I'm creating a form that will have multiple items to choose from and check in(add/increment) and checkout(minus/decrement)and it only works when the laptop variable is equal to 1. I want to set the total amount of an item and then whatever option they choose it'll either increment or decrement the variable associated with that item. I also can't figure out a way to make sure the variable won't reset every time the form closes and opens again.
function updateCount (form) {
//need to figure out way for count to not reset to total when closing
form
//only works when set to 1
var laptop=1;
if (form.option1.checked && form.optionin.checked) {
laptop++;
alert ("Your response has been recorded");
}
if (form.option1.checked && form.optionout.checked) {
laptop--;
alert ("Your response has been recorded");
}
if (form.option1.checked && form.optionout.checked && laptop===0) {
alert ("Item currently unavailable, choose another item");
}}
<h1>CS Equipment Renatal Form</h1>
<form>
<!--top of form with name and line break for text, don't need
anything with the Name: -->
Name:<br>
<!--creating the variable type for textfield and the name of it which
is fullname-->
<input type="text" name="fullname"><br>
<br>
<!--email textfield with line break after meaning new line-->
OU Email:<br>
<input type="email" name="ouemail"><br>
<br>
<!--doing the checkboxes for rental types with id since the id is
used in the script -->
Equipment Rental Type<br>
Laptop <input type="checkbox" name="option1" value="laptop"
id="option1"><br>
Tablet <input type="checkbox" name="option2" value="tablet"
id="option2"><br>
Monitor <input type="checkbox" name="option3" value="monitor"
id="option3"><br>
Camera <input type="checkbox" name="option4" value="camera"
id="option4"><br>
<br>
<!--doing checkboxes for checkout and check with id because its used
in script-->
Select One<br>
Check In <input type="checkbox" name="optionin" value="checkIn"
id="checkOut"><br>
Check Out <input type="checkbox" name="optionout" value="checkOut"
id="checkIn"><br>
<br>
<!--adding submit button and associating it with script function-->
<input type="submit" name="submit" value="submit"
onClick="updateCount(this.form)">
</form>
I assume var laptop=1; should hold the number of available laptops.
The problem here is that you're declaring it inside the function that should actually manage it - so you're basically resetting it with each call to this function.
To get around this you need to make it a global variable - one whichs is defined before and outside of function updateCount (form) { }.
Furthermore you should get rid of the onclick event on the input field and instead use the onsubmit event on the form itself. This way you can validate the form before it's actually submitted.
Take a look at this example:
var laptop = 1;
function updateCount(form) {
if (form.option1.checked && form.optionin.checked) {
laptop++;
alert("Your response has been recorded");
return true;
}
if (form.option1.checked && form.optionout.checked) {
laptop--;
alert("Your response has been recorded");
return true;
}
if (form.option1.checked && form.optionout.checked && laptop === 0) {
alert("Item currently unavailable, choose another item");
return false;
}
return false;
}
<h1>CS Equipment Renatal Form</h1>
<form onsubmit="return updateCount(this)">
<!--top of form with name and line break for text, don't need
anything with the Name: -->
Name:<br>
<!--creating the variable type for textfield and the name of it which
is fullname-->
<input type="text" name="fullname"><br>
<br>
<!--email textfield with line break after meaning new line-->
OU Email:<br>
<input type="email" name="ouemail"><br>
<br>
<!--doing the checkboxes for rental types with id since the id is
used in the script -->
Equipment Rental Type<br> Laptop <input type="checkbox" name="option1" value="laptop" id="option1"><br> Tablet <input type="checkbox" name="option2" value="tablet" id="option2"><br> Monitor <input type="checkbox" name="option3" value="monitor" id="option3"><br> Camera <input type="checkbox" name="option4" value="camera" id="option4"><br>
<br>
<!--doing checkboxes for checkout and check with id because its used
in script-->
Select One<br> Check In <input type="checkbox" name="optionin" value="checkIn" id="checkOut"><br> Check Out <input type="checkbox" name="optionout" value="checkOut" id="checkIn"><br>
<br>
<!--adding submit button and associating it with script function-->
<input type="submit" name="submit" value="submit">
Many issues here:
1- form.option1 is not a valid way of accessing the checkbox with id option1. Use document.getElementById("option1") instead. Same goes for optionin and optionout
2- Your button has type "submit", which will reload the page and reset your variable laptop (unless you save it using a cookie or localStorage). A simple way of preventing the button from refreshing the page is changing its type to "button".
3- As pointed out by #obscure's answer, you should declare your variable laptop outside of the updateCount function.
4- I believe you don't want users to select both "Check in" and "Check out" at the same time. For this, use radio buttons instead of a checkbox (note that both radio buttons have the same name attribute, so that you can't select both together).
var laptop=1; //will not reset as long as the page is not refreshed
//a way of preventing the from from refreshing the page is to change the button type to "button"
function updateCount (form) {
var laptop = document.getElementById("option1");
var option_in = document.getElementById("checkIn");
var option_out = document.getElementById("checkOut");
if (laptop.checked && option_in.checked) {
laptop++;
alert ("Your response has been recorded - Check In");
}
if (laptop.checked && option_out.checked) {
laptop--;
alert ("Your response has been recorded - Check Out");
}
if (laptop.checked && option_out.checked && laptop===0) {
alert ("Item currently unavailable, choose another item");
}
}
<!DOCTYPE html>
<html>
<h1>CS Equipment Renatal Form</h1>
<form>
<!--top of form with name and line break for text, don't need
anything with the Name: -->
Name:<br>
<!--creating the variable type for textfield and the name of it which
is fullname-->
<input type="text" name="fullname"><br>
<br>
<!--email textfield with line break after meaning new line-->
OU Email:<br>
<input type="email" name="ouemail"><br>
<br>
<!--doing the checkboxes for rental types with id since the id is
used in the script -->
Equipment Rental Type<br>
Laptop <input type="checkbox" name="option1" value="laptop"
id="option1"><br>
Tablet <input type="checkbox" name="option2" value="tablet"
id="option2"><br>
Monitor <input type="checkbox" name="option3" value="monitor"
id="option3"><br>
Camera <input type="checkbox" name="option4" value="camera"
id="option4"><br>
<br>
<!--doing checkboxes for checkout and check with id because its used
in script-->
Select One<br>
Check In <input type="radio" name="changeQty" value="checkIn"
id="checkIn"><br>
Check Out <input type="radio" name="changeQty" value="checkOut"
id="checkOut"><br>
<br>
<!--adding submit button and associating it with script function-->
<input type="button" name="submit" value="submit"
onClick="updateCount(this.form)">
</form>
</html>
In order to save the laptop variable if the page is refreshed, consider using a cookie, localStorage, or some server-side scripting.
Related
I am trying to make a manual verification system and want the user to check each checkbox associated with individual inputs if a value exists before submission else the form would throw an error.
I have implemented this, but it does not seem to work. Also, I was wondering if there was a better way of achieving the same wherein we avoid passing the parameters to the function.
Similar to how we can associate a submit button for a form using form by supplying the id.
<form>
<input type="text" name="inputFieldOne">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
<script>
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
if(fieldBox.value != ''){
checkBox = document.getElementsByName(checkbox)[0];
checkBox.required = true;
}
}
</script>
If you want to set the checkbox to be required when the field has a value, you should hook an event on the field, not the checkbox. input would make a good event for this:
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
let checkBox = document.getElementsByName(checkbox)[0];
// Require the checkbox when the field has a value
checkBox.required = fieldBox.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
Note that there's no need for those calls to getElementsByName: Just pass this into the function, and use nextElementSibling to access the checkbox:
function makeSureItIsSelected(field){
// Require the checkbox when the field has a value
field.nextElementSibling.required = field.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
That said, it seems odd to have the checkboxes at all. The presence of the field in the form data should be sufficient. But if the checkbox's value has to be in the form data, simply add it on submit without having a checkbox at all.
I'm working on a pizza website for school.
Here's the question I need to answer.
*Allow users to choose from three types of credit card: Visa, MasterCard and American Express. Based on the type of credit card, limit the length of the credit card number, 16 digits for Visa and MasterCard, 15 digits for American Express.
*
Currently, the page is setup so the user chooses whether he or she wants to pay when picking up the pizza or pay online using a credit card.
When online radiobox is checked, more radioboxes with credit card names appear.
html codes
<p> Payment Method</p>
<input id="paypickup" type="radio" name="rbRating"
value="Pick Up" checked />Pay on pickup
<input id="online" type="radio" name="rbRating"
value="online" />Online
<div id="hidden2" class="textinput">
<input id="visa" type="radio" name="cardtype"
value="Visa" onclick="showMe('visanum')"/>Visa
<input id="mastercard" type="radio" name="cardtype"
value="MasterCard" onclick="showMe('masternum')"/>MasterCard
<input id="americanexpress" type="radio" name="cardtype"
value="American Express" onclick="showMe('americaninfo')"/>American Express
</div>
<div id="visainfo">
<label for="visanum">Credit Card Number</label>
<input id="visanum" type="text" name="cardnum" maxlength="16" />
</div>
<div id="masterinfo">
<label for="masternum">Credit Card Number</label>
<input id="masternum" type="text" name="cardnum" maxlength="16" />
</div>
<div id="americaninfo">
<label for="americannum">Credit Card Number</label>
<input id="americannum" type="text" name="cardnum" maxlength="15" />
</div>
<button type="submit" value="Submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
JS code for hiding the credit card radio box until delivery is checked
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'paypickup') {
$('#hidden2').hide();
}
if($(this).attr('id') == 'online') {
$('#hidden2').show();
}
});
});
As you can see in the html codes, I tried to attempt this by creating multiple textboxes with maxlength. But I immediately realised this is inefficient and confusing.
I'm very new to these kind of stuff.
Create one input box for credit card number,initially disable the input box and on selection of the radio button for credit card enable the input box. HEre is change for both HTML and JS
HTML
<div>
Credit Card Number
<input id="creditCardNumber" type="text" name="cardnum" disabled/>
</div>
JS
function showMe(type) {
// clear previous value
$("#creditCardNumber").val('');
// enable the input and accept 16 digits for amex
if (type == "americaninfo") {
$("#creditCardNumber").attr({
maxlength: 16,
disabled: false
});
} else {
$("#creditCardNumber").attr({
maxlength: 15,
disabled: false
})
}
}
DEMO
If I were you, I wouldn't use all of those input:text. Instead, I'd use the data attribute to store all of the necessary data in it.
For example:
<input type="radio" name="cardtype" value="visa" data-maxLength="16"/>Visa
That way, you don't have to worry about hiding and showing several different boxes. Then, when the user clicks a new radio buttion, then you just have to set the maxlength attribute in the cardnumber input to the value of the data-attr
DEMO: https://jsbin.com/nufamixisi/edit?html,js,output
// Hide input
$(".cardInput").hide();
// User clicks on radio button so we need to show the input for card info
$('input:radio[name=cardtype]').click(function() {
// Show the input for card and delete old value
$("input:text[name=cardnum]").val("");
$(".cardInput").show();
// Get the maxLength set in the selected radio button
var ml = $(this).attr("data-maxLength");
$("input:text[name=cardnum]").attr("maxlength", ml);
});
I didn't throw logic in there to show/hide the card stuff based on cardpickup, etc. I think you can get that one ;)
I have a form in which i use multiple Checkbox. On Checkboxes i use JavaScript for validation If I checked all checkbox, it proceeds ahead otherwise it show an alert message.
My code is working Well
Problem
Because i have Two Button on my form and they have different functionality. I want to post value of Button on my action page
My Code goes here
<script>
function letter_submit(){
var pr = document.getElementsByName('pr'),
i = 0;
var allAreChecked = true;
for( ; i < pr.length; i++ )
{
if( pr[i].checked=='' ) {
allAreChecked = false;
}
}
if (!allAreChecked) {
alert("Please Check All Checkboxes");
exit;
} else {
alert("All OK");
document.getElementById("approve_letter").submit();
}
}
</script>
<form action="letter_approve_action.php" id="approve_letter" name = "approve_letter" method="POST" >
<input type="checkbox" name="pr" id="pr" value="" /> NL is appropriately addressed.
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Checked Press Release
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Applicable Methodology is rightly Marked
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Respective Sector Study on Website is Updated Within Last 12 Months.
</br>
<button type="button" name="btn_submit" id="btn_submit" value="Approve" onclick="letter_submit();">Approve</button>
<button type="button" name="btn_submit" id="btn_submit" value="Re - Submit" />Re-Submit</button>
</form>
On action page i use
echo $submit = $_POST ['btn_submit'];
and i got an error
Notice: Undefined index: btn_submit in C:\xampp\htdocs\Work_Que_Backup\login\pacra-all\w_q\nl\letter_approve_action.php on line 26
You may use <button> tag.
For example:
<form method="post">
<input type="text" name="myText" value="some text here..."/>
<button type="submit" name="myButton" value="buttonValue">Submit</button>
</form>
The label tht is displayed is "Submit" but you can access your button value from the server with a different value.
It will be accessible with php on server side as:
echo $_POST['myButton']; //buttonValue
The problem in your code is that your button is of type "button", and you trigger the POST by javascript - so the value for btn_submit is never set.
Change the button type to "submit" and move the event handler onclick=... to the form tag onsubmit=.... In your javascript function, you can the cancel the submit by returning false.
I am not sure if I am going about this correctly. I have a set of checkbox inputs. If someone selects the last check box all_users_check, I want a new form to appear where I will be listing all of the users in a drop down (haven't added the drop down yet). I thought I could do this by using the name of the input, but I am mistaken apparently as I am getting this error..
How else could I structure what I am doing so that if someone checks that option the new form displays?
<div class="user_dropdown">
<form action="">
<input type="checkbox" name="spectator_check" value=""> Spectators<br>
<input type="checkbox" name="member_check" value="" checked> Team Members<br>
<input type="checkbox" name="commissioner_check" value="" checked> Commissioner(s)<br>
<label for="all_users_check">
<input type="checkbox" name="all_users_check" value="" checked> Individual User<br>
</label>
</form>
</div>
<script>
$(".user_dropdown").hide();
$(".all_users_check").click(function() {
if($(this).is(":checked")) {
$(".user_dropdown").show();
} else {
$(".user_dropdown").hide();
}
});
</script>
This is how the page looks on load. Those fields are already checked for some reason.
Issues in your code.
.all_users_check that is looking for a class. Your element doesn't have a class so this isn't found. You can use a different selector to use the name attribute, https://api.jquery.com/attribute-equals-selector/.
This $(".user_dropdown").hide(); hides your whole form. You might want to move around your divs, or remove that altogether.
The checked attribute checks the field it is on. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
Use the checked attribute to indicate whether this item is selected
<div class="user_dropdown">
<form>
<input type="checkbox" name="spectator_check" value=""> Spectators<br>
<input type="checkbox" name="member_check" value=""> Team Members<br>
<input type="checkbox" name="commissioner_check" value=""> Commissioner(s)<br>
<label for="all_users_check">
<input type="checkbox" name="all_users_check" value=""> Individual User<br>
</label>
</form>
</div>
<script>
//$(".user_dropdown").hide();
$("input[name='all_users_check']").click(function() {
if($(this).is(":checked")) {
$(".user_dropdown").show();
} else {
$(".user_dropdown").hide();
}
});
</script>
isset is a language construct and can't accept anything other than a variable as indicated by this warning on the linked to manual page:
Warning isset() only works with variables as passing anything else will result in a parse error.
You are not passing in a variable to the isset function, you are passing in a constant value, basically an array with a single string all_users_check. This is not a variable because you are not assigning it to a variable name. Try this instead:
if(isset($_POST['all_users_check']))
Here the variable being passed in is the superglobal $_POST, and you are checking to see if the index all_users_check is set inside of that array.
Update
To check if an input is empty or not via javascript, take a look at this question.
Try using this script, you have set the state of check boxes as checked by default.
<div class="user_dropdown">
<form action="">
<input type="checkbox" name="spectator_check" value=""> Spectators<br>
<input type="checkbox" name="member_check" value=""> Team Members<br><!-- removed 'checked' from this line -->
<input type="checkbox" name="commissioner_check" value=""> Commissioner(s)<br><!-- removed 'checked' from this line -->
<label for="all_users_check">
<input type="checkbox" name="all_users_check" value="" > Individual User<br> <!-- removed 'checked' from this line -->
</label>
</form>
</div>
<script>
$(".user_dropdown").hide();
$(".all_users_check").click(function() {
if($(this).is(":checked")) {
$(".user_dropdown").show();
} else {
$(".user_dropdown").hide();
}
});
</script>
For the other issue of showing the hidden section again, try whether class all_users_check is visible to click.
How do I validate that the input text corresponding to the radio option is checked?
For example, using the image above:
If Contact 1's E-Mail radio option is selected, Contact 1's E-Mail text field cannot be blank, but Contact 1's Phone and US Mail text fields are still permitted.
If Contact 2's US Mail radio option is selected, Contact 2's US Mail text field cannot be blank, but Contact 2's Phone and E-Mail text fields are still permitted.
I have built the form above using the HTML below, but you can play with my Fiddle here: fiddle.
BEGIN UPDATE: I have a newer fiddle with better code here:
fiddle2
It has more instructions in the HTML and a closer attempt at my jQuery. For some reason, though, it still does not seem to be doing anything.
END UPDATE
I have tried naming the fields so that my jQuery can parse them, but that does not mean there is not a better way.
<body>
<form name="jp2code" action="#" method="POST">
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_PhoneRadio" name="group1"/>
<label for="group1_PhoneText">Phone:</label>
<input type="text" id="group1_PhoneText" name="group1_PhoneText"/>
<br/>
<input type="radio" id="group1_EMailRadio" name="group1"/>
<label for="group1_EMailText">E-Mail:</label>
<input type="text" id="group1_EMailText" name="group1_EMailText"/>
<br/>
<input type="radio" id="group1_USMailRadio" name="group1"/>
<label for="group1_USMailText">US Mail:</label>
<input type="text" id="group1_USMailText" name="group1_USMailText"/>
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_PhoneRadio" name="group2"/>
<label for="group2_PhoneText">Phone:</label>
<input type="text" id="group2_PhoneText" name="group2_PhoneText"/>
<br/>
<input type="radio" id="group2_EMailRadio" name="group2"/>
<label for="group2_EMailText">E-Mail:</label>
<input type="text" id="group2_EMailText" name="group2_EMaiText"/>
<br/>
<input type="radio" id="group2_USMailRadio" name="group2"/>
<label for="group2_USMailText">US Mail:</label>
<input type="text" id="group2_USMailText" name="group2_USMailText"/>
</span>
</fieldset>
<div>
<input type="submit" name="submit" value="submit" />
</div>
</form>
</body>
What is the best way to write the jQuery?
I am new to jQuery, but I attempted my hand at it based on some Show/hide examples.
What I created below does not work, but hopefully indicates what I am trying to accomplish.
$(function() {
$("input[type='radio']").change(function() { // when a radio button in the group changes
var id = $(this).id;
var index = id.indexOf('group');
if (index == 0) { // is there a better way to do this?
var groupN_Len = 7; // Length of 'groupN_'
var radio_Len = 5; // Length of 'radio'
var preStr = id.substring(0, groupN_Len);
$"input[name*='preStr']".validate = null; // clear validation for all text inputs in the group
var postStr = id.substring(groupN_Len + 1, id.Length() + 1 - radio_Len); // extract Phone, EMail, or USMail
$(preStr+postStr+'Text').validate({ rules: { name: { required: true } } });
}
});
});
To make sure that the radiobutton is checked for each field, add attribute required="" in one of the radiobuttons for each fieldset.
demo
OK, whatever radio button is selected in the Contact Group's Contact Preferences, that corresponding text field is required.
Here is where I am so far on my jQuery checking:
EDIT:
Modified with tilda's important detail about adding '.' to the class name.
Added Required Attribute: how to dynamically add REQUIRED attribute to textarea tag using jquery?
Removed Required Attribute: jquery removing html5 required attribute
Final code works and looks like this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("input[type='radio']").change(function() {
$('.'+$(this).attr('name')).each(function(index) {
$(this).removeAttr('required');
});
if($(this).is(':checked')) {
$('.'+$(this).attr('id')).each(function(index) {
$(this).prop('required',true);
});
}
});
$('#submit').click(function() {
$(this).validate();
});
});
Back to the HTML of the document: I did a lot of subtle editing to the text by creating specific ids and names for the radio buttons that matched up with the class names for the text controls.
Here is that end result:
<body>
<form name="jp2code" action="#" method="POST">
<div>For each field below, provide the Phone Number, E-Mail Address, and Street Address. <b>Indicate the preferred contact method using the radio button.</b></div>
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_Phone" name="group1"/>
<label for="group1_Phone">Phone:</label>
<input type="text" name="group1_PhoneText" class="group1 group1_Phone" />
<br/>
<input type="radio" id="group1_EMail" name="group1"/>
<label for="group1_EMail">E-Mail:</label>
<input type="text" name="group1_EMailText" class="group1 group1_EMail" />
<br/>
<input type="radio" id="group1_USMail" name="group1"/>
<label for="group1_USMail">US Mail:</label>
<input type="text" name="group1_USMailText" class="group1 group1_USMail" />
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_Phone" name="group2"/>
<label for="group2_Phone">Phone:</label>
<input type="text" name="group2_PhoneText" class="group2 group2_Phone" />
<br/>
<input type="radio" id="group2_EMail" name="group2"/>
<label for="group2_EMail">E-Mail:</label>
<input type="text" name="group2_EMailText" class="group2 group2_EMail" />
<br/>
<input type="radio" id="group2_USMail" name="group2"/>
<label for="group2_USMail">US Mail:</label>
<input type="text" name="group2_USMailText" class="group2 group2_USMail" />
</span>
</fieldset>
<div>
<input type="submit" value="Send" id="submit"/>
</div>
</form>
</body>
Let me explain what is going on in the jQuery, using the HTML above:
When a radio button's checked state changes, each control with a class name that matches the radio button's name attribute has the required property removed.
If a radio button is checked (i.e. checked=true), then each control with a class name that matches the radio button's id attribute has the required property added.
Finally, the validator seems to have to be run on a single form control (not on individual text controls like I was doing).
Here is the sample Fiddle that I ended with: Fiddle v8
At tilda: You didn't say much, but what you did say helped a lot!