How do I add radial/checkbox values to an object using jQuery? - javascript

So I'm trying to iterate through all the values of an HTML form and store them in a hashtable object of sorts.
The HTML for the form is pretty lengthy so I won't paste that here. But here is my JavaScript/jQuery so far:
readForm = function () {
var formValues = {};
$('form :input').each(function () {
var input = $(this);
formValues[input.attr('name')] = input.val();
});
console.log(formValues);
}
When I put these values in the form:
https://res.cloudinary.com/merrickcloud/image/upload/v1542089140/fdsa_z9re1e.png
I get this in the console:
https://res.cloudinary.com/merrickcloud/image/upload/v1542089140/fdsafsdaf_tmdib6.png
Why is the value on the radial and checkbox inputs incorrect? And what is that last undefined property?

For checkboxes you can use this:
Option 1:
$('#checkbox_id').prop('checked'));
Option 2:
$('#checkbox_id').is(':checked'));
Maybe in your case with the loop you can try this:
if(input.attr('type') == 'checkbox') {
input.is(':checked'));
}
...
The undefined property is maybe the Submit button. Is it like this?
<input type="submit" value="Submit Profile">

Related

How to get update all hidden fields with same name?

I have multiple hidden field with same name on html page like below
<input type="hidden" name="customerID" value="aa190809" />
I need to update values of all hidden field with same name i.e. customerID
I know how to do it(through Jquery) if html page contains single hidden field with customerID like below but not sure if there are multiple hidden field with same name
if(updatedCsrf !== null) {
var customerIDHidden = $("input[name='customerID']");
if(customerIDHidden !== null) {
customerID.val("some_value");
}
}
You can do something like this:
$("input[name=customerID]").each(function(){
this.value ="new value"
})
this will reference each DOM element. You can parse it again to jQuery DOM element by replacing this.value to $(this).val("new value") but since you only need to change the value its better with javascript vanilla
You can do that with pure JS,
var x = document.getElementsByName("customerID");
for(var i=0; i < x.length;i++){
x[i].value='new value';
}
Use jQuery each function
$("input[name='customerID']").each(function(){
$(this).val("some-value");
});

How do you return data from javascript into a html form?

I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable

Getting values of hidden checkboxes jQuery

I have a form with several checkboxes. Some values need to be true by default so i have made them hidden as:
<input type=checkbox name="<%= _key %>" checked="checked" style="display:none" />
To retrieve all values i'm doing:
var form_data = {}
$('form').find("input").each(function(i, e) {
if (e.checked)
form_data[e.name] = e.value;
});
But the hidden input fields are not coming. What am I doing wrong? How can I correct it?
Also im using underscore.js but i don't think this problem has to do anything with it.
For simplicity you can do this:
$(function(){ // put the code in doc ready
var form_data = {}
$('form').find(":checkbox:checked").each(function(i, e) {
form_data[e.name] = e.value;
});
});
So here i am suggesting you to just loop through the checked elems and put names & values in the javascript object.
But if you are interested in only hidden checked checkboxes $('form').find(":checkbox:checked:hidden").
I think you should do this jQuery way.
$('form').find("input").each(function(i, e) {
var jEl = $(this);
if(jEl.is(":checked"))
alert(1);
alert(jEl.attr("name"));
});

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

How to return a variable from a javascript function into html body

I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.
The function is here:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.
Thanks in advance!
Here's a little simpler approach.
First, make a few corrections to your HTML, and create a container to display the output:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Then change your script to this:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
...and place it just inside the closing </body> tag.
Click here to test a working example. (jsFiddle)
document.write takes a string, and outputs it as part of the HTML. This is not a live value that updates when the variable pointing at the string is updated.
For that, you will need to perform DOM manipulation.
Change your JavaScript function to something like that:
<script type="text/javascript">
function GetSelectedItem() {
len = document.f1.r1.length;
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
document.getElementById('test').textContent = document.f1.r1[i].value;
}
}
}
</script>
And then in the body:
<div id="test"></div>
As I put in the post. Using JQuery would make your life easy for this kind of task (and many others for the matter). The really nice thing about JQuery is that it often makes your JavaScript syntax much easier then you can learn the nitty gritty details of javascript as you go.
First, add the following script tag into your html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Now you have the JQuery API
Then you could rewrite the function like this.
function GetSelectedItem(btnRadio)
{
var jqElem = $(btnRadio);
$('#output').html(jqElem.attr('value')); //attr('<name of attributre'>) gets the value of the selected attribute
}
Your html would look like this
<form name = "f1">
<input type = "radio" name = "r1" value = "On" onclick="GetSelectedItem(this)">On
<input type = "radio" name = "r1" value = "Off" onclick ="GetSelectedItem(this)">Off
</form>
<div id="output">
</div>
More or less, the .html() can both get and set the html of the selected element. So we are just simply inserting the value into the div tag.

Categories

Resources