Unable to retrieve the value from a form with jQuery/Javascript - javascript

I'm trying to validate my form, but I can't seem to capture my form values! At a loss as to where to go now. I've tried a combination of jQuery and Javascript. Here's a snippet of my code.
HTML:
<form action="#" name="application-form" method="post" enctype="multipart/form-data">
<ul>
<li class="input-row">
<label for="app-resume">Resume</label>
<input type="file" id="app-resume" name="resume" />
</li>
<li class="input-row">
<label for="app-name">Full Name</label>
<input type="text" id="app-name" name="fname" />
</li>
<li class="input-row">
<label for="app-pnum">Phone Number</label>
<input type="number" id="app-pnum" name="pnum" />
</li>
<li class="input-row">
<label for="app-email">Email</label>
<input type="email" id="app-email" name="email" />
</li>
<li class="input-row">
<label for="app-info">Additional Information</label>
<textarea type="text" id="app-info" name="info"></textarea>
</li>
</ul>
<div class="btn-mssg-container">
<button type="submit" name="sbt-btn" id="sbt-btn">apply</button>
<p id="sbt-mssg" class="hidden">Thank you for applying.</p>
</div>
</form>
JS:
var myForm = document.forms["application-form"];
myForm.onsubmit = processForm;
function processForm(){
console.log(myForm.fname.value);
}
I've also tried:
function processForm(){
var inName = $("#app-name").val();
console.log(inName);
}
I'm getting nothing! Someone please put me out of my misery.

The first attempt at getting form values is called HTMLFormControlsCollection
1. Reference the form:
var FoRm = document.forms.FormID_or_NAME
OR
var FoRm = document.forms["FormID_or_NAME"]
OR
var FoRm = document.forms[0]
The last one using index number zero in bracket notation will work if the target <form> is the first on the page or the only <form> on the page.
2. Collect all of the form's form controls into an array-like object:
var formControlS = FoRm.elements
Step 2. was the crucial step that you were missing.
3. Now you can reference and get values from any form control under that specific <form>:
var foRmC = formControlS.FormControlID_or_NAME.value
OR
var foRmC = formControlS["FormControlID_or_NAME"].value
OR
var foRmC = formControlS[0].value
Details are commented in Demo
This localStorage feature cannot work in a Stack Snippet due to security measures. If you want to review a fully functional demo, then visit Plunk
Demo
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
justify-content: space-around;
flex-wrap: nowrap;
}
iframe {
display: inline-table;
max-width: 40%;
height: 100vh
}
#app0 {
max-width: 60%;
margin: 0 0 5px 15px;
}
label {
display: inline-block
}
/* Area code - Central Office code */
[type=number] {
width: 5ch
}
/* The last 4 digits - Station code */
label [type=number]:last-of-type {
width: 6ch
}
[type=email] {
width: 26ch
}
.hidden {
opacity: 0
}
#msg {
height: 60px;
overflow-x: hidden;
overflow-y: scroll;
border: 3px inset grey;
padding: 10px;
display: block;
}
</style>
</head>
<body>
<main id='main'>
<!-- On submit, form sends to a real test server
|| The target attribute value is the name of
|| iframe#display. Whenver data is tested thru
|| this server, it will send a response later.
-->
<form action="https://httpbin.org/post" id="app0" method="post" enctype="multipart/form-data" target='display'>
<fieldset id='set0'>
<label for="file0">Resume</label>
<input type="file" id="file0" name="resume">
<br>
<br>
<label for="name0">Full Name</label>
<input type="text" id="name0" name="name">
<br>
<br>
<label>Phone Number
<input type="number" id="area0" name="phone" min='100' max='999'>
<input type="number" id="cent0" name="phone" min='100' max='999'>
<input type="number" id="stat0" name="phone" min='0000' max='9999'>
</label>
<br>
<br>
<label for="mail0">Email</label>
<input type="email" id="mail0" name="mail">
<br>
<br>
<label for="info0">Additional Information</label>
<br>
<textarea id="info0" name="info" cols='28'></textarea>
<br>
</fieldset>
<fieldset id="set1">
<button id='btn' type="button" class=''>Process</button>
<button id='sub' type='submit' class='hidden'>Transfer</button>
</fieldset>
<output id="msg"></output>
</form>
<iframe name='display' src='about:blank' width='60%'></iframe>
</main>
<script>
/* The interface used to refer to form controls
|| is called HTMLFormControlsCollection
*/ // Reference the form
var xApp = document.forms.app0;
/*\\\\\\\\\\/IMPORTANT\//////////
This is the part that was in error
In order to refer to any form controls
of the referenced form, you must
collect them in an array-like object
using the .elements proerty //////*/
var xCon = xApp.elements;
// Then from the .elements reference by id
// A click event on a button--processForm
// is called
xCon.btn.onclick = processForm;
/* This function will gather all form values
|| into an array.
|| Then it stores that array in localStorage
|| Displays the data then hides the "Process"
|| button and reveals the "Transfer" button
*/
function processForm(e) {
var qty = xCon.length;
var data = [];
for (let i = 0; i < qty; i++) {
var formControl = xCon[i].value;
if (formControl !== null || formControl !== undefined || formControl !== "") {
data.push(formControl);
}
}
localStorage.setItem("data", JSON.stringify(data));
var stored = JSON.parse(localStorage.getItem("data"));
appX();
xApp.onsubmit = appX;
function appX(e) {
xCon.msg.value = stored;
xCon.btn.classList.toggle('hidden');
xCon.sub.classList.toggle('hidden');
}
}
/* Once the "Transfer" button is clicked, the
|| data is sent to the test server and the
|| test server responds back. The response is
|| captured and displayed in the iframe to the
|| right
*/
</script>
</body>
</html>

Related

Add fileupload input fields inside multiple div at a same time according to radiobox selection

I have a input field that takes numeric inputs. Then i have a button which display the number of divs as per that input. after displaying div there is two radio-box buttons (paired end and single end) if I select paired end then i want two file upload fields in each divs. and if i select single end then i want only one file upload fields in each div.
I have tried but fileupload fields working on only first div.
function CreateText() {
var text = `<div class="row border-top py-3">
<div class="col-md-3">
<label">sample name *</label></br>
<input type="sample" id="sample" name="sample[]">
</div>
<div class="col-md-3" style="display:none" id="showsingle">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename1[]">
</div>
</div>
<div class="col-md-3" style="display:none" id="showpair">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn">Remove</button>
</div>
</div>
</div>`;
var textCount = document.getElementById('textInput').value;
var html = '';
for (var i = 0; i < $('#textInput').val(); i++) {
html = document.getElementById('divDynamicTexts').innerHTML;
document.getElementById('divDynamicTexts').innerHTML = html + text.replace('', i);
}
}
function onlyOne() {
let SradioBox = document.getElementById("singleradio"),
Sfileupload = document.getElementById("showsingle"),
PradioBox = document.getElementById("pairedradio"),
Pfileupload = document.getElementById("showpair");
if (SradioBox.checked == true) {
Sfileupload.style.display = "block",
Pfileupload.style.display = "none";
} else if (PradioBox.checked == true) {
Pfileupload.style.display = "block",
Sfileupload.style.display = "none";
} else {
Pfileupload.style.display = "none",
Sfileupload.style.display = "none";
}
};
$(document).ready(function() {
$(document).on('click', '.remove_add_btn', function(e) {
e.preventDefault();
let row_item = $(this).parent().parent().parent();
$(row_item).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-center">
<input type="text" id="textInput" value="" />
<input type="button" id="" value="Create upload fields" onclick="CreateText();" />
<div class="col-md-4" id="filebutton">
<div class="form-group ">
<label for="form_need">Library Type *</label>
</br>
<div class="px-2">
<label for="myradio">Single end:</label>
<input type="radio" id="singleradio" name="check" onclick="onlyOne();">
<label for="myradio">Paired end:</label>
<input type="radio" id="pairedradio" name="check" onclick="onlyOne();">
</div>
</div>
</div>
</div>
<div id="divDynamicTexts"></div>
ID attributes must be unique. It would be better to remove the IDs altogether ( or change to dataset attributes perhaps ) and use a delegated event listener to process the various clicks related to the task of adding/removing dynamic elements.
In the code below all ID attributes were either removed entirely or changed to data-id type values.
To avoid the need to process different form file input fields at the server the file-input fields are named the same but have an index so can be identified more readily in PHP ( or whatever backend you have )
The delegated listener, because it is bound to the document, will work for all elements whether or not they are static or added dynamically and makes heavy use of the event.target property to help identify the element that invoked the event.
The label element was being used incorrectly previously. If the form-input is within the label then there is no need for the for="ID" syntax ( note that the ID should be the ID of the input element to which the label belongs! ) - as it was the label's appeared to have a for attribute which did not related to an element in the form!
Using querySelector and querySelectorAll you can easily identify nodes of interest within the DOM so button clicks or radio button selection can fire a query to find nodes that are relevant - thus simplifying the hiding/showing of the file input elements.
const strhtml = `
<div data-id="dynrow" class="row border-top py-3">
<div class="col-md-3">
<label>sample name *<input type="text" name="sample[]"></label>
</div>
<div class="col-md-3" style="display:none" data-id="single" data-role="file-field">
<div class="form-group">
<label>Upload file *<input type="file" name="filename[1]" /></label>
</div>
</div>
<div class="col-md-3" style="display:none" data-id="pair" data-role="file-field">
<div class="form-group ">
<label>Upload file *<input type="file" name="filename[1]" /></label>
<label>Upload file *<input type="file" name="filename[2]" /></label>
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn" data-id='remove'>Remove</button>
</div>
</div>
</div>`;
const _radio = document.querySelectorAll('[type="radio"][data-id]');
const _bttn = document.querySelector('[type="button"][data-id="add"]');
const _div = document.querySelector('#divDynamicTexts');
const _input = document.querySelector('input[type="number"][data-id="textInput"]');
let choice = false;
let qty = false;
/*
Disable radio buttons and the "Create" button initially
and enable when changes are made in the correct sequence.
1: select quantity -> enable radio bttns
2: select single or double -> enable "create" bttn
3: click bttn, create as per radio selection
*/
_input.addEventListener('change', e => {
_radio.forEach(n => {
n.disabled = e.target.value > 0 ? false : true;
});
qty=e.target.value;
});
document.addEventListener('click', e => {
if (e.target instanceof HTMLInputElement && e.target.dataset.id != null) {
/*
set global "choice" variable
and enable "Create" bttn.
*/
if (e.target.type == 'radio') {
choice = e.target.dataset.id;
_bttn.disabled = false;
}
}
/*
If the "choice" has been made the radio
buttons will be enabled. Based on radio
button selected create new HTML and then
unhide the appropriate single/pair DIV
element
*/
if (choice && qty > 0 && e.target.type == 'button') {
_div.innerHTML = '';
for (let i = 0; i < qty; i++) _div.insertAdjacentHTML('afterbegin', strhtml);
let expr = `div[data-id="${choice}"]`;
document.querySelectorAll(expr).forEach(n => n.style.display = 'block');
}
/*
unchanged: delete DIV & contents when "Remove" bttn is clicked.
*/
if (e.target instanceof HTMLButtonElement && e.target.dataset.id != null) {
if (e.target.dataset.id == 'remove') {
_div.removeChild(e.target.closest('[data-id="dynrow"]'));
}
}
});
body {
font-family: arial;
}
label {
display: block;
}
.px-2 {
display: inline-block;
}
.px-2 label {
display: inline-block;
margin: 0.5rem;
}
h2 {
font-size: 1.1rem;
margin: 1rem 0 0 0;
display: inline-block;
width: auto;
}
.inline {
display: inline;
margin: 0 1rem 0 0;
}
#divDynamicTexts {
min-height: 1rem;
margin: 2rem auto
}
div.row {
padding: 0.5rem;
border: 1px dotted grey;
margin: 0.5rem;
}
div[data-id='single'] .form-group label {
background: aliceblue
}
div[data-id='pair'] .form-group label {
background: lightsteelblue
}
div[data-id] .form-group label {
outline: 1px solid grey;
padding: 0.5rem;
margin: 0.5rem 0
}
.bold {
font-weight: bold
}
[disabled]{
border:1px solid red;
outline:2px solid red;
background:rgba(255,0,0,0.25);
}
<div class='text-center'>
<label class='inline bold'>Quantity:<input type='number' data-id='textInput' /></label>
<div class='col-md-4'>
<div class='form-group'>
<h2>Library Type</h2>
<div class='px-2'>
<label>Single end: <input type='radio' data-id='single' name='check' disabled /></label>
<label>Paired end: <input type='radio' data-id='pair' name='check' disabled /></label>
</div>
</div>
</div>
<input type='button' data-id='add' value='Create upload fields' disabled />
</div>
<div id='divDynamicTexts'></div>

Custom jQuery validation for duplicated repeating fields inside each container in one form

I'm trying to check if there are duplicated values for specific input field which is repeating inside each containing element.
The filed should be considered as a "duplicate" only if has the same value with other comparing field(s) and sharing the same parent container, which means the field can have the same value in 2 or more different containers. I now it sounds a bit confusing but I will add the markup and the current jQuery code so hopefully it will be more clear.
var attendees_group = $('.attendee-accordion-group'),
inputs = attendees_group.find('input[name*="_attendeeemail"]');
inputs.change(function(e) {
//Create array of input values
var ar = inputs.map(function() {
if ($(this).val() != '') return $(this).val()
}).get();
//Create array of duplicates if there are any
var unique = ar.filter(function(item, pos) {
return ar.indexOf(item) != pos;
});
console.log(unique.length);
//if duplicates
if (unique.length != 0) {
//do something
}
});
body {
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px
}
h3 {
display: block;
margin: 0 0 15px 0;
font-size: 18px;
}
h4 {
padding: 0;
margin: 0 0 15px 0;
font-size: 15px;
}
form {
padding: 20px;
}
.attendee-accordion-group {
padding: 40px;
border: 1px solid #999;
margin-bottom: 20px;
}
input {
border: 1px solid #ccc;
width: 50%;
line-height: 1;
height: 20px;
}
.button {
display: inline-block;
background: #0274be;
color: #fff;
padding: 10px 30px;
text-decoration: none;
border: none;
cursor: pointer;
margin-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<h3>Event Title 1</h3>
<div class="attendee-accordion-group">
<h4>Attendee 1</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_1__1" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_1__1" id="field_attendeelastname_1__1" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_1__1" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_1__1" id="field_attendeeemail_1__1" value="">
</span>
</p>
</div>
<h4>Attendee 2</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_1__2" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_1__2" id="field_attendeelastname_1__2" value="">
</span>
</p>
<label for="field_attendeeemail_1__2" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_1__2" id="field_attendeeemail_1__2" value="">
</span>
</p>
</div>
<h4>Attendee 3</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_1__3" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_1__3" id="field_attendeelastname_1__3" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_1__3" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_1__3" id="field_attendeeemail_1__3" value="">
</span>
</p>
</div>
</div>
<h3>Event Title 2</h3>
<div class="attendee-accordion-group">
<h4>Attendee 1</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_2__1" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_2__1" id="field_attendeelastname_2__1" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_2__1" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_2__1" id="field_attendeeemail_2__1" value="">
</span>
</p>
</div>
<h4>Attendee 2</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_2__2" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_2__2" id="field_attendeelastname_2__2" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_2__2" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_2__2" id="field_attendeeemail_2__2" value="">
</span>
</p>
</div>
</div>
<button type="button" class="button">Next</button>
</form>
<div class="error">
</div>
OK, so, the container is a div with a class .attendee-accordion-group, and inside, each text field labeled email, should be unique. I hope this clarifies issue a bit.
I used the js code for comparing field values from this answer
Right now all the "email" fileds, no matter of container are duplicates if values are the same, I was wondering if someone can help me with this.
If I understood you correctly, you are wanting to catch duplicates of the same input values in each "group" or each "event" in your example.
Here is something I put together that does just that. It will need some more adjustments like only outputting one error message for each duplicate value, instead of two. In the linked jsFiddle example, the validation only takes place on load, and not when the "Next" button is pressed. But this should push you in the correct position.
I added comments to the code to help you understand is going on.
jsFiddle: https://jsfiddle.net/mgqucrsz/1/
// will hold all the duplicate error message
var errorMessage = '';
// loops through each "group"
$('.attendee-accordion-group').each(function() {
// will hold all input values and names of each "group"
var inputs = [];
// loops through all inputs of the current group
$(this).find('input').each(function() {
// saves the value and name of each input for the current group
var input = {'name':$(this).attr('name'), 'value':$(this).val()};
// saves the current input/name into a growing list of inputs for this current group
inputs.push(input);
});
// loops through the inputs list generated in the previous loop for this group
for (var i = 0; i < inputs.length; i++) {
// shortens the reference to the current input
var input = inputs[i];
// returns the input that is duplicated
// 1. Loops though the inputs list
// 2. If the current index of the current input does not match the index of the item being looked up; in other words this will ignore itself, since matching with itself is technically a match
// 3. If the current input value matches with the looked up input
// 4. "&& item.value" makes sure that an input value exists, since empty values technically match with other empty values
var conflict = inputs.find(function(item) {return inputs.indexOf(item) !== i && item.value === input.value && item.value;});
// if conflict is not undefined; would be undefined if no duplicates were found
if (conflict) {
// append this error message to a growing error message
errorMessage += 'Value of form name ' + input.name + ' already exists on form name ' + conflict.name + '.<br>\n';
}
}
});
// finally output the error message
$('div.error')[0].innerHTML += errorMessage;

How to check if a jquery element is an `del` tag?

I have an HTML checkbox next to a paragraph. When the user check the box, I want to put a strike through the paragraph using css bootstrap.
To add the strike through, I should wrap the paragraph with <del></del> tag.
I am able to wrap the paragraph correctly with the <del></del> when the box is checked. However, I am unable to remove the <del></del> tag when the user uncheck the box.
My code seems to be failing to check if the element is a del.
I created a fiddler to show you what is happening https://jsfiddle.net/vo1npqdx/1335/
in the fiddler, you will see that the code if (display.is('del')) { .... } is failing so the code inside the if statement never gets fired.
I tried to print the html code to the console to make sure I am dealing with the correct element, and it is clearly showing the correct code.
How can I unwrap my paragraph from the del tag?
Here is my JS code
$(function(){
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
} else {
var firstDisplay = display.parent().children().first();
console.log(firstDisplay.html())
if (display.is('del')) { // this is failing
firstDisplay.unwrap();
}
}
});
});
Here is my HTML code
$(function(){
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
} else {
var firstDisplay = display.parent().children().first();
console.log(firstDisplay.html())
if (display.is('del')) { // this is failing
firstDisplay.unwrap();
}
}
});
});
body {
padding-top: 65px;
padding-bottom: 20px;
}
/* Set padding to keep content from hitting the edges */
.body-content {
padding-left: 15px;
padding-right: 15px;
}
/* Override the default bootstrap behavior where horizontal description lists
will truncate terms that are too long to fit in the left column.
Also, add a 8pm to the bottom margin
*/
.dl-horizontal dt {
white-space: normal;
margin-bottom: 8px;
}
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea,
.input-width-input {
max-width: 380px;
}
.uploaded-file-name {
max-width: 310px;
}
.help-block-standard {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
/* Vertically align the table cells inside body-panel */
.panel-body .table > tr > td
{
vertical-align: middle;
}
.panel-body-with-table
{
padding: 0;
}
.mt-5 {
margin-top: 5px !important;
}
.mb-5 {
margin-bottom: 5px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="http://laravel54.dev/assets/asset/6" accept-charset="UTF-8" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" name="_token" value="UA428wC4vxZgb9OmNCGBIkosCN4KuS49VgFiUTET">
<input name="_method" type="hidden" value="PUT">
<div class="form-group ">
<label for="name" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input class="form-control" name="name" type="text" id="name" value="Some new test" minlength="1" maxlength="255" required="true" placeholder="Enter name here...">
</div>
</div>
<div class="form-group ">
<label for="notes" class="col-md-2 control-label">Notes</label>
<div class="col-md-10">
<textarea class="form-control" name="notes" cols="50" rows="10" id="notes" maxlength="1000"></textarea>
</div>
</div>
<div class="form-group " style="margin-bottom: 5px;">
<label for="picture" class="col-md-2 control-label">Picture</label>
<div class="col-md-10">
<div class="input-group uploaded-file-group">
<label class="input-group-btn">
<span class="btn btn-default">
Browse <input type="file" name="picture" id="picture" class="hidden">
</span>
</label>
<input type="text" class="form-control uploaded-file-name" readonly>
</div>
<div class="input-group input-width-input">
<span class="input-group-addon">
<input type="checkbox" name="custom_delete_picture" class="custom_delete_file"> Delete
</span>
<span class="input-group-addon custom_delete_file_name">
<p>uploads/zCmPgC5yMor77DaM50nTTnSnxh4y75e7B06WUFFM.jpeg</p>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input class="btn btn-primary" type="submit" value="Update">
</div>
</div>
</form>
Maybe something like this?
var del = display.children().first();
console.log(del)
if (del.is('del')) {
del.contents().unwrap();
}
The del is element should be the first child of display. I've used console.log(del) because using html() is effectively giving you the innerHTML, which isn't particular helpful.
In your original code, display is your p element and this line was just going 'up one, down one', ending up back at the p:
var firstDisplay = display.parent().children().first();
This is the solution to your answer.
$(function(){
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
} else {
$(".custom_delete_file_name:eq(0) p").html($(".custom_delete_file_name:eq(0) p del").html());
}
});
});
But keep in mind you don't have to wrap it with a tag to make it strike through. You can simply add a css class or a style property with
text-decoration: line-through;
and toggle it.
This is the best approach.
A different approach... Intead of unwrap, just overwrite the p again with the content inside of del...
$('.custom_delete_file:checkbox').click(function(e){
var self = $(this);
var display = self.closest('.input-width-input').find('.custom_delete_file_name > p');
if (self.is(':checked')) {
display.wrapInner('<del></del>');
}
else {
display.html(display.find('del').text());
}
});
I hope it helps

How to fill div with values from form?

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);

How to revert change made by DOM?

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");
}
}

Categories