I have a html form with such structure:
...
<select name="Employee">
<option>a</option>
<option>b</option>
</select>
<input type="checkbox" name="email" value="Yes" unchecked>Include Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show()" id="refresh">
...
And a div:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:</div>
<div class="ft_tbl_data"></div>
</div>
How can I show my values in div section by pressing the button without reloading the entire page?
I know Javascript a bit, but unfortunately, didn't find the answer yet.
Thank you in advance!
Here is one solution, using unobtrusive vanilla javascript.
The function showData() runs when the button is clicked.
Then, the function showData():
gets the Boolean value of each checkbox (either true if checked or false if unchecked)
rewrites the Boolean value as a string (a value of true becomes 'Yes' and a value of false becomes 'No')
rewrites the relevant data field, including the string.
function showData() {
var emailValue = document.querySelector('input[value="email"]').checked;
var phoneValue = document.querySelector('input[value="phone"]').checked;
var data = document.getElementsByClassName('data')[0];
var dataFields = data.getElementsByTagName('div');
if (emailValue === true) {emailValue = 'Yes';} else {emailValue = 'No';}
if (phoneValue === true) {phoneValue = 'Yes';} else {phoneValue = 'No';}
for (var i = 0; i < dataFields.length; i++) {
switch (i) {
case (0) : dataFields[i].textContent = 'E-Mail: ' + emailValue; break;
case (1) : dataFields[i].textContent = 'Phone: ' + phoneValue; break;
}
}
}
var button = document.querySelector('input[type="button"]');
button.addEventListener('click',showData,false);
form, .data, label, input[type="button"] {
display: block;
}
form, .data {
float: left;
width: 200px;
}
input[type="button"] {
margin-top: 24px;
}
<form>
<label><input type="checkbox" name="contact" value="email" unchecked>Include Email Contact</label>
<label><input type="checkbox" name="contact" value="phone" unchecked>Include Phone Contact</label>
<input type="Button" value="Generate">
</form>
<div class="data">
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_meta">Phone:</div>
</div>
set some IDs for your divs you wish to take/assign values from/to and put this code
IncludeEmailCheckBox is for your "include Email" checkbox
EmailToDiv is for your div to get the email
EmailFromDiv is for your input for Email
IncludePhoneCheckBox is for your "include Phone" checkbox
PhoneToDiv is for your div to get the Phone
PhoneFromDiv is for your input for Phone
function show(){
if (document.getElementById("IncludeEmailCheckBox").checked){
document.getElementById("EmailToDiv").innerHTML = document.getElementById("EmailFromDiv").innerHTML ;}
if (document.getElementById("IncludePhoneCheckBox").checked){
document.getElementById("PhoneToDiv").innerHTML = document.getElementById("PhoneFromDiv").innerHTML ;}
return false;
}
Remember to change IDs as nessesary
Get elements of class by calling document.getElementsByClassName(class_name)
Example javascript code below
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var x = document.getElementsByClassName("ft_name");
x[0].innerHTML = form.name.value;
x = document.getElementsByClassName("ft_tbl_meta");
x[0].innerHTML = form.email.value; // name email is one provided in form
// Do same for all other classes
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<input type="checkbox" name="email" value="Yes" unchecked>Include
Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show(this.form)" id="refresh">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
here is your view (I updated) using Jquery:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:<span id="email_here"></span></div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:<span id="phone_here"></span></div>
<div class="ft_tbl_data"></div>
</div>
Now fetching and printing values:
var Employee = $( "select[name=Employee]" ).val();
$('.ft_name').html(Employee);
var email = $( "input[name=email]" ).val();
$('#email_here').html(email);
var phone = $( "input[name=phone]" ).val();
$('#phone_here').html(phone);
var jobTitle = $( "input[name=jobTitle]" ).val();
$('.ft_pos').html(jobTitle);
Related
I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}
I have a form for which I should write validation logic.
Let's say there's an input field like this.
<div class="group1"><label>Product code</label> <input id="code" name=""code" type="text" class="control1"></div>
If I want to make it a required field how do I write the logic?
I don't have access to the CSS files. But there's an input like this which I can use which has a red outline.
<div class="group1 row has-error">
<div><input type="text" class="control1"></div>
</div>
I have to give the code in JavaScript or jQuery.
Get an element and set true on required property.
const input1 = document.getElementById('code');
input1.required = true;
const input2 = document.querySelector('div.group1>div>input.control1');
input2.required = true;
<form>
<div class="group1"><label>Product code</label>
<input id="code" name="code" type="text" class="control1">
</div>
<div class="group1 row has-error">
<div>
<input type="text" class="control1">
</div>
</div>
<input type="submit">
</form>
I think this is what you need
$("#formSubmit").submit(function(e) {
e.preventDefault();
var error_text = "<div class='text-danger error_val'>Cannot be empty</div>"
var data = $("#formSubmit").serializeArray();
var allInputs = $("#formSubmit input");
for(var i=0; i<data.length; i++){
if(data[i].value.length == 0){
$(".group1").addClass('has-error');
var errorDiv = $(allInputs)[i].closest('.has-error');
$(error_text).insertAfter( errorDiv );
}
}
});
.has-error input{
border: 1px solid #f00;
}
.text-danger{
color:#f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formSubmit">
<div class="group1 row">
<label>Product code</label>
<input id="code" name="code" type="text" class="control1" >
</div>
<button type="submit" id="submitButton">Save</button>
</form>
I know it`s too late but you can use these functions to make an input required/optional
function makeFieldRequired(element, elementName) {
let jqueryObj = $(element);
jqueryObj.attr('title', `${elementName} is required`);
jqueryObj.attr('required', 'true');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function makeFieldOptional(element) {
let jqueryObj = $(element);
jqueryObj.removeAttr('required');
jqueryObj.removeAttr('title');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function refreshFormValidtion(form) {
$(form).removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
i have created one form with dynamically created fields. and i have a one check box with unique ID . when user clicks that check box then only those two fields are visible ("name and age"). after clicking only "age" field need to be validate .
here is my code :
$(document).ready(function() {
$('#person').click(function() {
function formValidator(){
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
});
});
$(document).ready(function() {
$('#person').click(function() {
$('#name').attr('required','required');
$('#age').attr('required','required');
});
});
style is :
.selectContainer{
display:none;
}
input[type=checkbox]:checked ~ .selectContainer {
display:block;
}
Html code is:
<form action="" method="post" onSubmit="return formValidator()">
<label for="name">Any Accompanying Person ?:</label>
<input type="checkbox" name="person" id="person" >Yes
<div class="selectContainer">
<br>
<label>Person Details</label>
<p>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
</div>
</div>
<h3>Choose Your Payment Option</h3>
<h1>
<div style="padding-left:150px;">
<input type="radio" name="type" value="visa">VISA/MASTER CARD:<br />
<input type="radio" name="type" value="cheque"> CHEQUE/DEMAND DRAFT<br />
<input type="radio" name="type" value="neft">NEFT<br /><br/>
</div>
<label></label>
<input type="submit" name="submit" value="submit"><br />
</form>
problem: the form field "age" is validating successfully by clicking check box ("Any Accompanying Person ?:"). problem is when user try to submit the form without clicking that check box then all so its asking for validate . how get salutation for this ? please help
The validator is within a click handler, which should live outside of that (On the base on the document.ready()).
Also if you just want to validate when that checkbox is clicked you could check it within the javascript and select it via the name of the checkbox (If it has a unique ID each time).
function formValidator(){
var age = document.getElementsByName('age[]');
if($("input[name = 'chk[]']").prop('checked')){
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
Bring all javascript functions outside of click events. Try this formValidator function
function formValidator(){
if($("#person").is(":checked")) {
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
So I made a simple javascript form validator which creates a box with the error message using DOM. But I can't figure out a way how to reset all these changes when i reset the form using
<button type="reset">
I would like to know how it's done please.
Thanks.
The Code
<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");
if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}
//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>
<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}
.vis{
display: none;
font-size: 12px;
}
</style>
</head>
<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>
<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">
<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">
<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The browser cannot magically figure out what has to be done to reset the custom changes.
However you can listen to the reset event of the form using element.addEventListener.
DEMO
HTML
<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>
JS
//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');
//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form
//hide the errors container
errorsCt.style.display = 'none';
});
});
If you want to reset the form, as if user hadn't made any selections or added any input, then just set all form element values to their default value, or empty.
jsFiddle
<div>
<form action="/echo/html" method="get">
<input type="text" placeholder="username" />
<br/>
<input type="password" placeholder="password" />
<br/>
<input type="checkbox" value="test" data-default="checked" checked="checked"/>
<br/>
<button type="reset" value="reset" onclick="resetForm()">reset</button>
<br/>
</form>
<div id="err">Some error message</div>
</div>
window.resetForm = function () {
var fields = $('input'),
uname, pass, check;
uname = $(fields.get(0));
pass = $(fields.get(1));
check = $(fields.get(2));
$("#err").text("");
uname.val('');
pass.val('');
if (check.attr("data-default") == "checked") {
check.attr("checked", "checked");
} else {
check.removeAttr("checked");
}
}
What I'm trying to do is to redirect people to a link depending of what they have summited on the form (the link is built using the values from the form fields)
This is the Form:
<form id="form">
<div class="formbox">
<div class="radio-toolbar">
<input type="radio" id="iconapp1" name="department" value="1250"/>
<label for="iconapp1">PP</label><br>
<input type="radio" id="iconapp2" name="department" value="944"/>
<label for="iconapp2">EP</label><br>
</div>
<div class="radio-bar1">
<input type="radio" id="enginemake1" name="enginemake" value="6"/>
<label for="enginemake1"> Chevrolet</label><br>
<input type="radio" id="enginemake2" name="enginemake" value="8"/>
<label for="enginemake2"> Chrysler</label><br>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar3">
<select name="powerrange">
<option id="powerrange1" value="28">100</option>
<option id="powerrange2" value="128">200</option>
<option id="powerrange3" value="228" selected>300</option>
</select>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar4">
<input type="radio" id="location1" name="location" value="store"/>
<label for="location1"> America (NT - ST)</label><br>
<input type="radio" id="location2" name="location" value="store.au"/>
<label for="location2"> Australia and Oceania</label><br>
</div>
<div class="radio-bar2">
<input onclick="goToPage();" type="button" class="buttonmyapp" value="Submit" />
</div>
</div>
</form>
The link I'm trying to build using the values selected will look like this:
http://{location}.mydomain.com/product-catalog.aspx?section=-{department}-{enginemake}-{powerrange}-
Each bracketed section needs to be replaced by the value of the select with the corresponding name.
First include the jquery library link or download js and link
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function goToPage(){
var location = $('input[name=location]:checked').val();
var department = $('input[name=department]:checked').val();
var enginemake = $('input[name=enginemake]:checked').val();
var powerrange = $('select[name=powerrange]').val();
window.location.href = "http://"+location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
}
</script>
After the goToPage function on the submit button validates the response change the src attribute of the form should work fine.
So in jQuery it should look something like
var location = $('input[name=location]:checked', '.radio-bar4').val();
var dept = $('input[name=location]:checked', '.radio-bar4').val();
var engine = $('input[name=enginemake]:checked', '.radio-bar1').val();
var power = $('powerrange').val() ;
var domain = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+dept+"-"+engine+"-"+power+"-";
$("#form").attr("action", domain);
you can try this
HTML
<select id="powerrange" name="powerrange">
JAVASCRIPT
function goToPage()
{
var location;
var department;
var enginemake;
var powerrange;
pName = document.getElementById('powerrange');
powerrange = pName.options[pName.selectedIndex].value;
var form = document.getElementById('form');
var ele = form.getElementsByTagName('input');
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute('type')=='checkbox')
{
if(ele[i].getAttribute('name')=='department')
{
if(ele[i].checked)
department = ele[i].value;
}
else if(ele[i].getAttribute('name')=='enginemake')
{
if(ele[i].checked)
enginemake = ele[i].value;
}
else if(ele[i].getAttribute('name')=='location')
{
if(ele[i].checked)
location = ele[i].value;
}
else;
}
}
var url = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
form.setAttribute('action',url);
form.submit();
}