Add value to hidden value by onclick checkbox - javascript

I have a form with some input checkboxes. For example:
<input type="checkbox" name="felhasznal_1" id="felhasznal_1" onclick="felhasznal(this)">
<input type="checkbox" name="felhasznal_2" id="felhasznal_2" onclick="felhasznal(this)">
<input type="checkbox" name="felhasznal_3" id="felhasznal_3" onclick="felhasznal(this)">
I have hidden value for a form:
<input type="hidden" name="felhasznalas" value="">
My form is named like this:
<form method="post" name="ujpartner_ceg" enctype="multipart/form-data" id="ujpartner_ceg">
And I want to add a masked id for the value of felhasznalas. But I have 2 forms with the same inputs, so that's why I named the forms, and I want to access to them by getelementByid using the form name.
Here is my javascript (generated by php):
function felhasznal() {
document.ujpartner_ceges.getElementById('felhasznalas').value = '|x|';
if (document.ujpartner_ceges.getElementById('felhasznal_1').checked) {
document.ujpartner_ceges.getElementById('felhasznalas').value = document.ujpartner_ceges.getElementById('felhasznalas').value + '1|x|';
}
if (document.ujpartner_ceges.getElementById('felhasznal_2').checked) {
document.ujpartner_ceges.getElementById('felhasznalas').value = document.ujpartner_ceges.getElementById('felhasznalas').value + '2|x|';
}
if (document.ujpartner_ceges.getElementById('felhasznal_3').checked) {
document.ujpartner_ceges.getElementById('felhasznalas').value = document.ujpartner_ceges.getElementById('felhasznalas').value + '3|x|';
}
}
What did i do wrong?
EDIT: I get this error:
TypeError: document.ujpartner_ceges is not a function.
NOTICE: I have a form with the same inputs named ujpartner_magan!

first, I would use document.getElementById without the "ujpartner_ceges."
and the main problem is that your inputs don't have IDs, if you use the IDs exactly like the names your function will work as intended.

This might be a problem: onclick="felhasznal(this)"
But your function takes no parameter...
function felhasznal() {
Add a parameter to function:
function felhasznal(myCheckbox) {
or
remove the this from the onclick handler.

your hidden input has no ID just a name.
use <input type="hidden" id="felhasznalas" value=""> instead.
The ID must be unique for the DOM (page) not just the form, so if you have several forms you must prefix the control eg: <input type="hidden" id="form1_felhasznalas" value="">.
Then use document.getElementById instead of document.ujpartner_ceges.getElementById.
I would also take a couple of hours to learn jquery, it's an amazing javascript-cross-browser-framework / helper for doing things like this :) !
Here is a fiddle: http://jsfiddle.net/3AguQ/
I have changed the hidden inputs to text so you can se the results...
Here is some code:
<script>
function felhasznal(prefix)
{
document.getElementById(prefix + '_felhasznalas').value = '|x|';
if (document.getElementById(prefix + '_felhasznal_1').checked)
{
document.getElementById(prefix + '_felhasznalas').value = document.getElementById(prefix + '_felhasznalas').value + '1|x|';
}
if (document.getElementById(prefix + '_felhasznal_2').checked)
{
document.getElementById(prefix + '_felhasznalas').value = document.getElementById(prefix + '_felhasznalas').value + '2|x|';
}
if (document.getElementById(prefix + '_felhasznal_3').checked)
{
document.getElementById(prefix + '_felhasznalas').value = document.getElementById(prefix + '_felhasznalas').value + '3|x|';
}
}
</script>
<form method="post" enctype="multipart/form-data">
<input type="hidden" id="form1_felhasznalas" value="">
<input type="checkbox" name="felhasznal_1" id="form1_felhasznal_1" onclick="felhasznal('form1')">
<input type="checkbox" name="felhasznal_2" id="form1_felhasznal_2" onclick="felhasznal('form1')">
<input type="checkbox" name="felhasznal_3" id="form1_felhasznal_3" onclick="felhasznal('form1')">
</form>
<form method="post" enctype="multipart/form-data">
<input type="hidden" id="form2_felhasznalas" value="">
<input type="checkbox" name="felhasznal_1" id="form2_felhasznal_1" onclick="felhasznal('form2')">
<input type="checkbox" name="felhasznal_2" id="form2_felhasznal_2" onclick="felhasznal('form2')">
<input type="checkbox" name="felhasznal_3" id="form2_felhasznal_3" onclick="felhasznal('form2')">
</form>

Related

Get dynamically value from data attribute

How do I get and store the value of the data-id attribute? The value inside of it changes on button click, so I need a method that gets the value as it changes. I've tried document.getelementbyid/name/value but I get the only get the value stored from the first button click. The method I'm using now $(this).data('id') returns nothing. Thanks
mustache file:
<td>
<form id="Form" action="./downloaddoc" method="GET">
<input type="hidden" name="p" value="download"/>
<input type="hidden" name="fileid" data-id="{{file_id}}"/>
<input class="button download_button" type="submit" value="Download">
</form>
</td>
js:
$(document).on('click', '.download_button', download_doc);
function download_doc(event) {
event.preventDefault();
var id = $(this).data('id');
console.log(id);
window.location.href = window.location.href + '?p=download&id=' + fileid;
}
You're searching for data attribute in the download button and not in the input field where it is actually present.
Add a class/id to the input field so that you can find it.
When you click on the button find the closest form and then find the input field which contains file id and extract the file id from it.
<td>
<form id="Form" action="./downloaddoc" method="GET">
<input type="hidden" name="p" value="download"/>
<!-- Added a class to the input field -->
<input type="hidden" name="field" class="input-download-file" data-id="{{file_id}}"/>
<input class="button download_button" type="submit" value="Download">
</form>
</td>
Javascript:
$(document).on('click', '.download_button', download_doc);
function download_doc(event) {
event.preventDefault();
// Find the closest form
var form = $(this).closest('form');
// Find the input field which constains the download file id
var input = $(form).find(".input-download-file");
// Get the file id
var id = $(input).data('id');
console.log(id);
window.location.href = window.location.href + '?p=download&id=' + fileid;
}

Add delimter to data posted to form

The post data is separated by commas. I need to add a delimiter (concatenate) such as '|' to all the input fields (text, textarea, select, etc) to the post data submitted by a form, but I do not want to change the value of the fields themselves in the form.
<form action="somepage.php" method="post">
<div class"line">
<input type="text" class="sometext" name="desc" />
</div>
<div class"line">
<input type="text" class="sometext" name="desc" />
</div>
<div class"line">
<input type="text" class="sometext" name="desc" />
</div>
<input type="submit" id="submitbutton" />
</form>
I tried the below code, but it changes the data in the form itself
$(document).on('click', '#submitbutton', function(){
$('.sometext').each(function(){
var descVal=''
var descVal = $('.sometext').val() + '|';
$(this).val(descVal);
});
});
When using $('.sometext').val() you're not specifying exactly which element you want the value of. Change:
var descVal = $('.sometext').val() + '|';
To:
var descVal = $(this).val() + '|';
Alternatively you can simply use:
$(this).val(this.value + '|');
$(document).on('click', '#submitbutton', function(){
$('.sometext').each(function(){
$(this).val(this.value + '|');
});
});

I can't post to google?

Here is the code for a small program where you put the keyword, choosing the search engine and then pressing "Search" button to search. But google don't leave me to POST. What else I can do?
EDIT: Yahoo and Bing works fine.
ERROR
405. That’s an error.
The request method POST is inappropriate for the URL
/search?q=computer. That’s all we know.
HTML
<form name="search" action="" method="Post" onSubmit="redirect()">
<input type="text" name="keyword"><br />
Google<input type="radio" name="ch" checked>
Yahoo!<input type="radio" name="ch">
Bing<input type="radio" name="ch"><br />
<input type="submit" value="Search">
</form>
Javascript
<script type="text/javascript">
var searchengine=[
"http://google.com/search?q=",
"http://search.yahoo.com/search?p=",
"http://bing.com/search?q="
];
function redirect()
{
var radioButtons = document.getElementsByName("ch");
for (var x = 0; x < radioButtons.length; x++) {
if (radioButtons[x].checked)
{
document.search.action = searchengine[x] + document.search.keyword.value;
}
}
}
</script>
But google don't leave me to POST. What else I can do?
Use GET rather than POST in your form, or just assign the relevant URL to window.location.
Here's an example of the latter. Some other changes:
Added some labels.
Changed how you're matching up the selected radio button and the searchengine to make it more robust/maintainable.
Changed the name of the search form. Since this gets dumped on the window object I avoid simple words like "search".
Properly encoded the keyword (you must encode URI parameters).
Live copy | Live source
HTML:
<form name="searchForm" action="" method="GET" onSubmit="return doSearch()">
<input type="text" name="keyword">
<br>
<label>Google<input type="radio" name="ch" value="google" checked></label>
<label>Yahoo!<input type="radio" name="ch" value="yahoo"></label>
<label>Bing<input type="radio" name="ch" value="bing"></label>
<br>
<input type="submit" value="Search">
</form>
JavaScript:
var searchengine = {
"google": "http://google.com/search?q=",
"yahoo": "http://search.yahoo.com/search?p=",
"bing": "http://bing.com/search?q="
};
function doSearch() {
var frm, index, cb;
frm = document.searchForm;
if (frm && frm.ch) {
if (frm.ch) {
for (index = 0; index < frm.ch.length; ++index) {
cb = frm.ch[index];
if (cb.checked) {
window.location = searchengine[cb.value] +
encodeURIComponent(frm.keyword.value);
}
}
}
}
return false; // Cancels form submission
}
"http:google.com/search?q=", is not formatted properly..
try "http://google.com/search?q="

How to manipulate Get query?

I have the following form from http://regain.sourceforge.net/:
<form name="search" action="search.jsp" method="get">
<p class="searchinput">
<b>Suchen nach: </b>
<input name="query" size="30"/>
<select name="order" size="1" ><option selected value="relevance_desc">Relevanz</option><option value="last-modified_asc">Dokumentendatum aufsteigend</option><option value="last-modified_desc">Dokumentendatum absteigend</option</select>
<input type="submit" value="Suchen"/>
</p>
</form>
the search form works fine. The URL looks like the following:
http://localhost:8080/regain/search.jsp?query=queryfieldvalue&order=relevance_desc
Now I want to add a checkbox to manipulate the value of the input field query.
If the checkbox is checked then the query value should look like filename:"queryfieldvalue"
http://localhost:8080/regain/search.jsp?query=filename%3A%22queryfieldvalue%22&order=relevance_desc
What's the best way to do this? Javascript? Do you have a short example for me because I'm really new to javascript.
Thanks a lot in advance.
one way with pure javascript (without jquery) would be
<script type="text/javascript">
function handler()
{
var check = document.getElementById('check');
var query = document.getElementsByName('query')[0];
if(check.checked)
{
query.value = "filename:\"" + query.value + "\"";
}
else
{
query.value = query.value.replace(/^filename:"/, "").replace(/"$/, "");
}
}
</script>
<form>
<input type="text" name="query" />
<input type="checkbox" id="check" onclick="handler()" />box
</form>
it should more or less work, it would be safer if you give query input field an id and then reference it by id, not name
if you use jQuery, something like this should do:
<input type="checkbox" id="chkQuery">Pass queryfield</input>
<script>
$(document).ready(function{}
$("#chkQuery").click(function(){
if ($(this).is(':checked'))
$("input[name='query']").val("filename:queryfieldvalue");
else
$("input[name='query']").val("queryfieldvalue");
});
});
</script>

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});

Categories

Resources