Please help, faced with difficulties while trying to store data via sessionStorage
I have a simple form and desire to read data from form inputs and append it to the table and store that data in the table during the session
HTML
Name: <input type="text" id="name"/>
Email: <input type="text" id="email"/>
Tel: <input type="text" id="tel"/>
Street: <input type="text" id="street"/>
City: <input type="text" id="city"/>
State: <input type="text" id="state"/>
Zip: <input type="text" id="zip"/>
<button id="myForm" type="button">Add Costumer</button>
JS
$(document).ready(function(){
if(sessionStorage.length>0){
display()
}
})
$("#myForm").on("click", function(){
save()
$(":input").val(""); //clean fields of the form
});
function save(){
var name= $("#name").val();
var email= $("#email").val();
var telephone= $("#tel").val();
var street= $("#street").val();
var city= $("#city").val();
var state= $("#state").val();
var zip= $("#zip").val();
var inputArray = [name, email, telephone, street, city, state, zip];
for(i in inputArray){//storing input data
sessionStorage.setItem(i, inputArray[i])
};
display()
}
function display(){
var restoredName = sessionStorage.getItem(0);
var restoredEmail = sessionStorage.getItem(1);
var restoredTel = sessionStorage.getItem(2);
var restoredStreet = sessionStorage.getItem(3);
var restoredCity = sessionStorage.getItem(4);
var restoredState = sessionStorage.getItem(5);
var restoredZip = sessionStorage.getItem(6);
//append filled information from the form to the table and 2 buttons - Update and Remove
$("#listContent table").append( "<tr>" +
"<td>" + restoredName + "</td>"+
"<td>" + restoredEmail + "</td>"+
"<td>" + restoredTel + "</td>"+
"<td>" + restoredStreet + "</td>"+
"<td>" + restoredCity + "</td>"+
"<td>" + restoredState + "</td>"+
"<td>" + restoredZip + "</td>"+
"<td>" + "<button>Update</button>" + "</td>" +
"<td>" + "<button>Remove</button>" + "</td>" +
"</tr>");
}
the issue is that only the last submit is stored and displayed in table, but not all submits that were performed during the session
I guess sessionStorage is rewrited every time user clicks submit with new input values. And I have no idea how to increase the storage with every new submit.
Please advise, how to fix this issue? thanks
The code you gave just write the input array in session storage.
If you want to store several inputArrays in session storage, the best way would be to generate an identifier, and to serialize your input array to store it.
The way you generate the identifier for your array is up to you. To serialize it, you could use
var dataToStore = JSON.stringify(inputArray);
Then you would use
sessionStorage.setItem(myGeneratedId, dataToStore);
Finally to read your data:
var myArraySerialized = sessionStorage.getItem(myGeneratedId);
var myArray = JSON.parse( myArraySerialized );
As JSON parse may fail it is a good idea to try...catch it.
The question is: Why are you using indexes? sessionStorage is a key-value object and the best way to use it is to set proper key, that you can access it later.
sessionStorage.setValue('Key', 'Value');
If you want to save everything from the array you'll need to stringify it:
sessionStorage.setValue('KeyName' JSON.stringify(Data));
And when you get it back use JSON.parse()
var dataArray=JSON.parse(SessionStorage.getItem('KeyName'));
Related
I try to dynamically add an input field to a form. It works fine except one thing:
I try to fill a with $.each, but this only works for the first dynamically added if I add more, the stays empty..
the #add button is in the initial form:
append:
$('#add').click(function() {
i++;
$dynamic_field').append('' +
'<h1>Sensor '+i+'</h1> ' +
'<tr id="row'+i+'">
'<td><div class="form-group">\n' +
'<label for="InputSensorType">Sensor Type*</label>\n' +
'<select class="form-control" id="InputSensorType" name="sensorType[]"></select>\n'
'</div></td>\n +'
'<td>
<button type="button" name="copy" id="copy" class="btn btn-primary">Copy this sensor
</button></td><tr>');
Each:
var jsarray = <?php echo json_encode($sensors)?>;
$.each(jsarray, function (index, value) {
$('#InputSensorType').append(('<option value='+index+'>'+value+'</option>'));
});
Can anyone help me?
Try this
var jsarray = '<?php echo json_encode($sensors)?>';
var obj = jQuery.parseJSON(jsarray);
var data = '';
$.each(jsarray, function (index, value) {
data +='<option value='+index+'>'+value+'</option>';
});
$('#InputSensorType').append(data);
function edit_row(id)
{
document.getElementById("monthly_val"+id).innerHTML="<input type='text' id='monthly_text"+id+"' value='"+monthly+"' onkeyup='this.value=Comma(this.value)' 'required'>";
}
The above code is an example of my input field and i want to put required validation so that the data will not be saved when the field is empty.
Try this...
var a = document.getElementById("monthly"+id),
b = document.createElement("INPUT");
b.setAttribute("pattern", "regexp string");
b.setAttribute("formnovalidate", " false");
b.setAttribute("type", "text");
//add other attributes
a.appendChild(b);
/*
Just replace the regexp string*/
if you have textbox id then you can easily find and then you can check input empty or not. you need use this process before saving data.
document.getElementById("monthly_val" + id).innerHTML = "<input type='text' id='monthly_text" + id + "' value='" + monthly + "' onkeyup='this.value=Comma(this.value)'>";
if ($('#monthly_text' + id + '').val() == '') { alert('wala'); }
use this. it helps you
I'm trying to do a form field validation. I got the text fields validation working from here, but not for the radio buttons as I am unsure of where I did wrong.
HTML:
<div>
<label>Gender:</label>
<input type="radio" name="gender" class="gender" value="Female" >Female</input>
<input type="radio" name="gender" class="gender" value="Male" >Male</input> <br/>
<span class="error">This field is required</span>
</div>
jQuery:
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;;
if (is_checked) {$('.gender').removeClass("invalid").addClass("valid");}
else {$('.gender').removeClass("valid").addClass("invalid");}
});
This is the real-time validation code which I played around on. It does not work however. When submitting the form, my error message still shows up regardless of which radio button I choose.
$("#studentsform").submit(function(event) {
var form_data = $("#studentsform").serializeArray();
var error_free = true;
for (var input in form_data){
var element = $("#"+form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {error_element.removeClass("error").addClass("error_show"); error_free = false;}
else {error_element.removeClass("error_show").addClass("error");}
}
if (!error_free) {
event.preventDefault();
}
else {
idcount++
var Surname = $('#surname').val();
var Name = $('#name').val();
var Gender = $('.gender:checked').val();
var Addr = $('#address').val();
var Email = $('#email').val();
var Phone = $('#phone').val();
$("#tblData tbody").append( "<tr>"+ "<td>" + idcount + "</td>"+ "<td>" + Surname + "</td>"+
"<td>" + Name + "</td>"+
"<td>" + Gender + "</td>"+
"<td>" + Addr + "</td>"+
"<td>" + Email + "</td>"+
"<td>" + Phone + "</td>"+
"<td><button class='btnEdit'>Edit</button><button class='btnDelete'>Delete</button></td>"+ "</tr>");
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
}
});
After checking all real-time validation, on the submit button I do the code above, which is to double check for validations and if it is error free, i append all the inputs into a row.
Preview:
As you can see from the picture above, even after clicking on Insert, my error message still shows up.
The author's code are very structured, but if anyone has a better and simpler way, could you please provide me a sample solution?
Much thanks!
Looks like you need
$("input[name=gender]").prop("checked");
which will return a boolean matching the checked value
Edit:
If you want to keep your code the same, you need to add the .valid class to all the gender-classed inputs. This way, when you check one radio, it will make both valid, and you shouldn't get an error.
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;
if (is_checked){
$('.gender').removeClass("invalid").addClass("valid");
} else {
$('.gender').removeClass("valid").addClass("invalid");
}
});
I'm trying to make a form with some input fields and then take those input fields and place them into a textarea field.
Here is my JS script:
function sayDetails() {
var name = document.getElementsByName("userName"),
address = document.getElementsByName("userAddress"),
city = document.getElementsByName("userCity"),
email = document.getElementsByName("userEmail"),
final_txt = "Name: " + name + "Address: " + address + "City: " + city + "Email: " + email;
document.getElementById("outputArea").innerHTML = final_txt;
return false;
}
And here is my html:
<div class="form">
<form name="userDetails">
Name: <input type="text" name="userName" id="uName" required><br>
Address: <input type="text" name="userAddress" id="uAddress"><br>
City: <input type="text" name="userCity" id="uCity"><br>
Email: <input type="text" name="userEmail" id="uEmail" required><br>
</form>
<br>
<input type="submit" form="userDetails" value="Submit form" onclick="sayDetails();">
<input type="button" form="userDetails" id="resetBtn" value="Reset" />
<br>
<textarea style="width:600px;height:100px;" id="outputArea" disabled></textarea>
</div>
After running it however, in the textarea field it shows this:
Name: [object NodeList]<br/>Address: [object NodeList]<br/>City: [object NodeList]<br/>Email: [object NodeList]
And what I would want it to display is:
Name: name here
Address: address here
City: city here
Email: email here
Where did I go wrong, and how can I make my code more efficient? Also, a little help to show me how to make the form input field lined up would be much appreciated!
EDIT: After a few correction here and there, and thanks to you guys I was able to do it correctly.
Here is the new and revised JS script that correctly displays the details the way I want it.
function sayDetails() {
var name = document.getElementById("uName").value;
var address = document.getElementById("uAddress").value;
var city = document.getElementById("uCity").value;
var email = document.getElementById("uEmail").value;
var final_txt = "Name: " + name + "\n" + "Adress:" + address + "\n" + "City: " + city + "\n" + "email:" + email;
document.getElementById("outputArea").innerHTML = final_txt;
}
document.getElementsByName returns NodeList (collections of nodes)
For getting first item you should use like this:
var name = document.getElementsByName("userName")[0],
address = document.getElementsByName("userAddress")[0],
city = document.getElementsByName("userCity")[0],
email = document.getElementsByName("userEmail")[0]
And then for each Node you can get the value, for example:
name.value
Well if you print node list objects as a string then its primitive value will be printed. No wonder in that. Try to write your code like below,
final_txt = "Name: " + name[0].value + "Address: " + address[0].value + "City: " + city[0].value + "Email: " + email[0].value;
And I saw there are ids assigned with input elements, better use that instead of name for selecting the elements like,
var name = document.getElementById("uName").value;
Use document.getElementById remember is unique
function sayDetails() {
var name = document.getElementById("uName").value,
address = document.getElementById("uAddress").value,
city = document.getElementById("uCity").value,
email = document.getElementById("uEmail").value,
final_txt = "Name: " + name + "Address: " + address + "City: " + city + "Email: " + email;
document.getElementById("outputArea").innerHTML = final_txt;
return false;
}
i am using this code to access all the hidden elements from a form:
function get_hidden_val(ids,form_id)
{
var get_check_val = document.getElementById(ids);
if(get_check_val.checked){
var div = $('<div></div>')
.appendTo('form#bulk_add_cart')
.attr('id',"bulk_"+form_id)
$("form#" +form_id).find('input[type="hidden"]').each(function(){
var value =$(this).val();
var name = $(this).attr("name");
var tags = "<input type='hidden' value='" + value + "' name='"+name+"'>";
$('div#' +form_id).append(tags);
});
}
else
{
$("form#bulk_add_cart").find('div#' +form_id).remove();
}
}
My problem is when I click the first checkbox it give me the result but when i click the second checkbox it doesn't and also the another problem is when i click first checkbox it shows total hidden elements but when i second time checked it, it show 4 less ?
Please suggest a solution.
Thanks
#user704302: Missing >, update var tags to --
var tags = "<input type='hidden' value='" + value + "' id='"+id+"'>";