I am trying to make a javascript function that modifies the hidden value of a form depending on what button you click and then send it via post to a page that processes it.
I checked that the value is modified correctly, but when the post is sent the default value is sent.
Any help?
Here the js function:
function citar(key)
{
document.getElementById('esta-cita').value=key;
document.getElementById('form-cita').submit();
}
EDIT: I did this and now it works. jQuery!
function citar(key)
{
$("#ncita").attr("value", key);
$('#form-cita').submit();
}
Your main problem here is that you are using
document.getElementsByName
which returns an array. Therefor the implementation of key is invalid.
if you are using jQuery you might use
$('[name=esta-cita]').each(function() {
$(this).val(key); //this will insert key to all esta-cita named parameters, even if only 1
});
if you only have 1 parameter of this kind so :
$('[name=esta-cita]').val(key);
});
i deeply recommand you to use jQuery jQuery website
in javascript's case i would have recommand you to use
document.getElementById on 'esta-cita' as well.
if you want to insert key to all elements in javascript i would recommand a very efficient way :
document.getElementsByName('esta-cita').forEach(function(entry) {
entry.value = key; //entry indicates a cell in the array
This returns an array of elements, so you'll have to iterate through it like a normal array.
function citar(key)
{
document.getElementsByName('esta-cita').value=key;
document.getElementById('form-cita').submit();
}
Should be:
function citar(key)
{
var derp = document.getElementsByName('esta-cita');
for (var i=0;i<derp.length;i++) {
derp[i].value = key;
}
document.getElementById('form-cita').submit();
}
Or just document.getElementsByName('esta-cita')[0].value=key; if you just want the first one
Try with,
document.getElementsByName('esta-cita')[0].value=key;
you can access to a length property document.getElementsByName('esta-cita').length to know how many elements are matched
Alternatively you can try this
function citar(key)
{
document.forms['form-cita'].esta-cita.value = key;
document.forms['form-cita'].submit();
}
HTML should be like
<form action="putActionHere" method="POST" enctype="multipart/form-data" id="form-cita">
<input type="hidden" name="esta-cita" id="esta-cita" value="yourval">
...
<input type="submit" value="Submit" onClick="citar('keystring');" />
</form>
Related
I'm about to code, in Javascript some code (involving looping on each <input> and adding listeners):
allowing, after keypress, to save all <input> values to localStorage
restore all <input> values from localStorage in the case the page/browser has been closed and reopened on the same page
But maybe is there an automatic way, provided by the browsers?
e.g. by adding an attribute to <input>, similar to <input autofocus> (which is not related here)
Question: is there an autosave feature of <form> <input> HTML tags?
As far as I know, there is no built-in way to do that, you should do it manually;
function persist(thisArg) {
localStorage.setItem(thisArg.id, thisArg.value);
}
<input id="test" onchange="persist(this)" />
persist and retrieve all together:
function persist(event) {
localStorage.setItem(event.target.id, event.target.value);
}
// you may use a more specific selector;
document.querySelectorAll("input").forEach((inputEl) => {
inputEl.value = localStorage.getItem(inputEl.id);
inputEl.addEventListener("change", persist);
});
<input id="test" />
there is no automatic way to do that.
you have two options :
save the data by code
example:
localStorage.setItem('testObject', JSON.stringify(yourObject)); // for storing data
JSON.parse(localStorage.getItem('yourObject')); // for retrieving data
code snippet:
// for saving data
function saveData(el) {
localStorage.setItem(el.id, JSON.stringify(el.value));
}
// for retrieving data on page load
function getData() {
var inp = document.getElementById("inp");
inp.value = JSON.parse(localStorage.getItem('inp')) || "";
}
<body onload="getData()">
<input id="inp" onchange="saveData(this)" />
</body>
try a helper library like persisto
Based on the accepted answer, here is a one-liner that can be useful:
document.querySelectorAll('input:not([type="submit"])').forEach(elt => { elt.value = localStorage.getItem(elt.name); elt.addEventListener("change", e => { localStorage.setItem(e.target.name, e.target.value); }); });
It serializes/deserializes the <input>s to localStorage, indexed by their attributes name.
I have some input in my form,now I want to get the json object from the form without some input named point,What's wrong with my code?I have to remove them.It seems not work for not() function.How to fix my code?
<form id="myform">
<input name='student' value='a'/>
<input name='student' value='b'/> '
...
<input name='point' value='90'/>
<input name='point' value='95'/>
</form>
Now I only want to submit the student data to the server.So I write the code:
var data = $('#myform').not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
but the result still have point data.What's wrong with not() function?
breaking down your code $('#myform') selects your form, in this case, only one object, then you filter that object with .not("input[name='point']") but there is only one object which is the form itself.
You want to filter the form's children instead, so just add .children() like this:
var data = $('#myform').children().not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
Hope this will help you.
$('#myform input[name!=point]').serializeArray()
Your selector is faulty.
$('#myform').not("input[name='point']").serializeArray()
...says, "Serialise the form with ID 'myForm' which is not also an input and has the name 'point'.
Rather, you mean: "Serialise the form with ID 'myForm' but omit its child inputs with name 'point'.
Here's a non-jQuery way, using native FormData.
//get the form as form data
var fd = new FormData(document.querySelector('#myform'));
//delete any elements pertaining to [name=point]
fd.delete('point');
//et voila; this shows we retain only the student fields
for (var key of fd.keys()) alert(key);
Very new to JavaScript/HTML, help!
I have 2 text boxes and a submit button. I am trying to retrieve the data from each of them using JavaScript and for the time being, simply put them into an alert box.
However, on clicking the button, the alert just reads 'undefined', help!
Here's a code snippet:
function submitApp() {
var authValue = document.getElementsByName("appAuthor").value;
var titleValue = document.getElementsByName("appTitle").value;
alert(authValue);
}
<input type="text" name="appAuthor" size="" maxlength="30" />
<input type="text" name="appTitle" maxlength="30" />
<input type="button" value="Submit my Application!" onclick="submitApp()" />
getElementsByName() returns a list. So you can grab the first item in the list:
document.getElementsByName("appAuthor")[0].value
.getElementsByName() method returns an array-like node list, so you'll need to specify an index in order to retrieve a specific input's value (because the value property only applies to DOM elements, not an entire list).
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
Just add this jQuery to a document.ready section like this:
$(document).ready(function() {
$('#submit').on('submit', function(e) {
e.preventDefault();
submitApp();
});
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
});
<input type="submit" id="submit" value="Submit my Application!">
If you want to submit the form remove the e.preventDefault();, but if you just want the value updated keep it in there to prevent form submition.
You could potentially change the button type into a submit-type and do something like this:
$('body').find('form').on('submit', function(e){
e.preventDefault();
var authValue = $('input[name="appAuthor"]').val();
var titleValue = $('input[name="appTitle"]').val();
//...here do whatever you like with that information
//Below empty the input
$('input').val('');
})
Or just interpret the form as an array to make your life easier and clean the code up.
When you use getElementsByName or getElementsByClassName, it returns array of elements, so you should put index to access each element.
authValue = document.getElementsByName("appAuthor")[0].value;
I'm getting the values of checkboxes when a user submits the form and storing their values as an array, so the form looks like this:
<!-- gym_create.html - I have removed the other inputs in the form for brevity -->
<form class="create-gym" role="form">
<input type="checkbox" name="gymTags" value="Bodybuilding" id="tagBodybuilding" class="tag-checkbox"/>
<input type="checkbox" name="gymTags" value="Powerlifting" id="tagPowerlifting" class="tag-checkbox"/>
<button type="submit" class="btn create-form-submit">Save gym</button>
</form>
And then I collect that information in my JS file associated with the form:
// gym_create.js - I have removed the other values I collect apart from the gymName value for brevity
Template.gymCreate.events({
"submit .create-gym": function (e) {
e.preventDefault();
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]:checked').map(function() {
return $(this).val();
}).get()
});
// Collect values from form when submitted
var gymDetails = {
gymName: $(e.target).find('[name=gymName]').val(),
gymTags: tagOutput,
}
// Call method here
}
});
I can then output these in my template using {{gymDetails.gymTags}} but this produces the following in the browser:
"{"TAGOUTPUT":["BODYBUILDING","POWERLIFTING"]}"
What I want is a way to store the values as JSON so they are like so:
{"gymTags": {
"bodybuilding": "true",
"powerlifting": "false"
}}
So that I can output each tag on it's own and also access only tags which are 'true' (that were checked) later on.
Does anyone know how I go about this? I wrangled with it all yesterday and the best I could come up with was the =JSON.stringify
I don't want to pass the entire form to JSON, just the checkboxes, is JSON.stringify what I want to be doing or am I barking up the wrong tree.
I think this should do it. You were just returning the just the value of the inputs. You want to return a json object, where the value is the "index" and the checked property is the "value" of the object.
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]').map(function() {
var op = {};
op[this.value] = this.checked;
return op;
}).get()
});
Edit: as noted by Da Rod, to use both checked and unchecked checkboxes, you must remove the ":checked" selector.
Since your selector is only grabbing items that are checked, they are all "true". That being the case, you need to change the way you are using "map" to add properties to tagOutput.
var tagOutput = {}
$(':checkbox[name=gymTags]').map(function() {
tagOutput[this.value] = this.checked;
})
});
In this example
<form id="form1">
<input type="text" name="style">
</form>
<form id="form2">
<input type="text" name="id">
</form>
you cannot access form1's style declaration or form2's id, since the named inputs shadow the corresponding properties.
The same holds for other properties too
Any workarounds?
Edit:
getAttribute works for id, obviously. But not for style, childNodes, tagName etc.
I'm looking for something like this:
getDomProp = (function() {
if (window.__lookupGetter__) {
var cleanForm = document.createElement('form');
return function(form, key) {
// works in Firefox, fails in Opera:
return cleanForm.__lookupGetter__(key).call(form);
};
} else if (Object.getOwnPropertyDescriptor) {
return function(form, key) {
// does not work at all:
// return Object.getOwnPropertyDescriptor(cleanForm, key).get.call(form);
}
} else {
throw 'Not supported.';
}
})();
Fiddle
This will still work:
form.getAttribute('id');
PS. Don't name your inputs that in production code :)
Use getAttribute to get the corresponding form attributes: http://jsfiddle.net/6d8sx/3/
alert('id: ' + form.getAttribute('id'));
Edit: getAttribute seems to work in IE9, FF5 (not sure about others).
However, naming your elements that way will cause problems down the line (if not your code, then some library or plugin might get confused).
Access them using .getAttribute();
http://reference.sitepoint.com/javascript/Element/getAttribute
yuse jquery: $('#form1').css(), or $('#form2').attr('id').