I have this function:
function selectCheckedAnswer(){
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
for (let i = 0; i < checkbox_checked.length; i++) {
let item = checkbox_checked[i];
form.appendChild(item);
}
}
It is not working as expected. When debugging, there are generated one form to each checkbox checked. (because I inserted the form inside of the For loop, I know)
When I debug the code above, 2 forms are being sent to the controller
image here
...but I just get 1 of the forms and 1 checked checkbox:
image here
What I need is to send only one form with the checkboxes selected to the controller.
I think you are looking for this:
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
checkbox_checked.forEach(element => {
form.innerHTML += element.innerHTML;
});
Related
i have wrote a function to activate onsubmit"" in the form.
In the function(JavaScript) i try to fill variables with input from the fieldset.
On troubleshooting i immediately found out that all the input gets cleared before i can save them into the variables.
I know that this is not how forms are used but i do like how it points out the fields that still needs to be filled.
so is there a way or someone how figured out a way to outsmart the submit to do something(function) before the refresh? or is there absolutely no way?
function objectfill() {
var vnaam = document.getElementById('Voornaam').value;
var anaam = document.getElementById('naam').value;
var mail = document.getElementById('email').value;
var tele = document.getElementById('mobiel').value;
var rknr = document.getElementById('rijksregister').value;
var actie = document.getElementById('workshop').value
var k = document.getElementsByName('Room');
var room
for (var i = 0; i < k.length; i++) {
if (k[i].checked) {
room = k[i].value;
}
}
var personeel = new personeelgegevens(pnr, vnaam, anaam, mail, tele, rknr,
actie, room);
console.log(personeel)
This was the function i used onsubmit="objectfill()"
I wanted to fill the object but obviously not working.
You just need to prevent that submit from happening so that your JavaScript can run, by calling event.preventDefault(). Also, try using element.addEventListener() instead of inline event properties.
// Assuming a form that looks like
<form id="myform">
// Do
const form = document.getElementById('form')
form.addEventListener('submit', event => {
// prevent the form from submitting
event.preventDefault()
// The rest of your form code here
})
How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});
I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascript variable. How can I do this?
<!-- Javascript -->
<script>
function getLoc(){
var all_location_id = document.getElementByName("location[]").value;
var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 -->
}
<script>
foreach($cityrows as $cityrow){
echo '<input type="checkbox" name="location[]" value="'.$cityrow['location_id'].'" />'.$cityrow['location'];
echo '<br>';
}
echo '<input name="searchDonor" type="button" class="button" value="Search Donor" onclick="getLoc()" />';
var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
This is a variation to get all checked checkboxes in all_location_id without using an "if" statement
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
I you are using jQuery you can put the checkboxes in a form and then use something like this:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>
I have an Ext.form.Panel containing a grid and some text fields for editing each row in the grid. It is very similar to this: http://dev.sencha.com/deploy/ext-4.0.2a/examples/writer/writer.html , only that there is no AJAX involved; my data store is local.
How can I submit the grid's rows via a standard POST?
If I simply do myForm.submit(), there are two issues:
The fields for editing the grid's rows are being validated. They should be ignored when submitting the form.
No data from the grid is being submitted.
The only solution I see is to somehow prevent the fields from being validated and create some hidden fields containing the data from each row. Is there any better option?
Thank you in advance!
Here's the solution I used:
For ignoring certain fields from the form upon submitting, I've overwritted the getFields() method of the form. Nasty, I know. In the code below, the fields with an 'ignoreInMainForm' property will be ignored.
Ext.getCmp('myForm').getForm().getFields = function() {
var fields = this._fields;
if (!fields) {
var s = [],
t = this.owner.query('[isFormField]');
for (var i in t) {
if (t[i]['ignoreInMainForm'] !== true) {
s.push(t[i]);
}
}
fields = this._fields = Ext.create('Ext.util.MixedCollection');
fields.addAll(s);
}
return fields;
}
For submitting the grid's data, I encode all the rows in a single JSON object that I add in the form's baseParams.
var myItems = myStore.getRange();
var myJson = [];
for (var i in myItems) {
myJson.push({
'a': myItems[i].get('a'),
'b': myItems[i].get('b'),
...
});
}
Ext.getCmp('formHiddenId').setValue(Ext.encode(myJson ));
That partially worked for me - in ExtJS 4.0.2a, I couldn't add to the baseParams, so instead I triggered the send handler to instead do:
function prepareToSendForm(a, b) {
var myItems = Ext.getCmp('grid-links').store.getRange();
var myJson = [];
for (var i in myItems) {
myJson.push({
'title': myItems[i].get('title'),
'url': myItems[i].get('url'),
'refreshes': myItems[i].get('refreshes')
});
}
//Update the hidden field to be the JSON of the Grid
for (var i=0, len=Ext.getCmp('roomCreateForm').getForm()._fields.items.length; i<len; i++) {
var item = Ext.getCmp('roomCreateForm').getForm()._fields.items[i];
if (item.name=='roomLinks') {
Ext.getCmp('roomCreateForm').getForm()._fields.items[i].inputEl.dom.value=Ext.encode(myJson);
break;
}
}
Ext.getCmp('roomCreateForm').submit();
}
Which worked lie a charm (but isn't very plug-and-play). I had to create a hidden field (named roomLinks above) in the form, and the second for loop above finds that and replaces the value with the JSONed results.
Im trying to set the action of a form with javascript!
How come it wont work on this code: (what happens is that the page gets submitted to itself, as in 'action="#"'
function validateForm() {
var nr_of_pics=document.getElementById("annonsera_nr_pics").value;
var name = document.getElementById("annonsera_name");
var tel = document.getElementById("annonsera_tel");
var email = document.getElementById("annonsera_email");
var area = document.getElementById("annonsera_area");
var community = document.getElementById("annonsera_area_community");
var category = document.getElementById("annonsera_category");
var subcats = document.getElementById("annonsera_subcats").getElementsByTagName("select");
var headline = document.getElementById("annonsera_headline");
var description = document.getElementById("annonsera_des");
var price = document.getElementById("annonsera_price");
if (nameValid(name) && telValid(tel) && emailValid(email) && areaValid(area) && communityValid(community) && categoryValid(category) && subcatsValid(subcats) && headlineValid(headline) && descriptionValid(description) && priceValid(price)){
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
alert (form);
return true;
}
return false;
}
and the form:
<form name="annonsera" id="annonsera" method="post" enctype="multipart/form-data" onSubmit="return validateForm();">
BY the way, the alert box wont show up either!
ALSO, setting the form action manually in HTML works fine, and the form is validated properly!
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
These lines aren't doing what you seem the think they're doing.
The first line is creating a variable called 'form', and copying the form's current action into that variable as a string. The second line then sets the variable to a new value, but the form's action isn't being changed because the variable only contained a copy of the form's action.
This would be what you're after:
var formElement = document.getElementById("annonsera");
formElement.action = "bincgi/verify_"+category+".php";
However, I don't know why your alert box isn't showing up at all. Are you certain that all the validity methods are actually being passed?
Try this:
document.getElementById("annonsera").action = "bincgi/verify_"+category+".php";
The problem with your code is that you first read the action attribute into a variable:
var form = document.getElementById("annonsera").action;
and then you set the form variable to a new string but this won't update the value of the DOM element.
Give it simple like
document.annonsera.action = "bincgi/verify_"+category+".php"
and to Submit the form
document.annonsera.submit()