This question already has answers here:
Get checkbox value in jQuery
(21 answers)
Closed 5 years ago.
I have the following:
$('.checkbox').click(function () {
console.log(this);
$.ajax({
type:'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}});
return false;
});
Now where I do the console.log(this), it returns:
<div class="ui checkbox checked">
<input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
<label>Women</label>
</div>
How do I get the input name (gender)? And whether the checkbox is checked out or not?
This answer here show you how to retrieve the element by name. However, the tricky part here is that your have brackets within the name itself. So, to get around this, you need to add quotes " around the name like in the following example below.
Once you have the element, you can simple do .prop('checked') to retrieve the current value.
$('.checkbox').click(function () {
console.log(this);
var theValue = $('input[name="gender[women]"]').prop('checked'); //<--HERE IS HOW YOU GET THE VALUE
console.log(theValue);
$.ajax({
type:'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}});
return false;
});
You can use the method find of jQuery to get the input object, then to check if the gender woman is checked you can use prop method of jQuery as well.
$('.checkbox').click(function () {
// to get the input
var $input = $(this).find('input');
// to check if the checkbox is checked or not
console.info($input.prop('checked'));
$.ajax({
type:'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
<input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
<label>Women</label>
</div>
Use $(this).find(":checkbox") to get the checkbox. Then you can use .attr('name') to get the name, and .is(":checked") to get whether it's checked.
You shouldn't return false because that prevents clicking on the checkbox from actually changing the box's state.
$('.checkbox').click(function() {
console.log(this);
var checkbox = $(this).find(":checkbox");
var name = checkbox.attr("name");
var checked = checkbox.is(":checked");
console.log(name + "is " + (checked ? "" : "not ") + "checked");
$.ajax({
type: 'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
<input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
<label>Women</label>
</div>
If I interpret the question correctly, you can pass an HTML string response to jQuery() to create a jQuery object from the HTML string, then call .attr("name") and .prop("checked"):
var input = $(response).find("input");
console.log(input.attr("name"), input.prop("checked"));
How do I get the input name (gender)? And whether the checkbox is
checked out not?
If you are trying to get the .name and .checked property values of clicked element you can call .querySelector() chained to this: .checkbox element, with selector "input[type=checkbox]"; .getAttribute() with "name" as parameter, .replace() with RegExp /^\w+\[|\]/g to get word within "[", "]"; and .checked property of the matched element returned by .querySelector()
$(".checkbox").click(function () {
var input = this.querySelector("input[type=checkbox]");
var _name = input.getAttribute("name").replace(/^\w+\[|\]/g, "");
var checked = input.checked;
console.log(_name, checked);
$.ajax(/* settings */);
});
Related
This question already has answers here:
Does ID have to be unique in the whole page?
(14 answers)
Closed 4 years ago.
I have many forms (created by user with an "add" button) every of this forms have an unique ID, but the input inside "Form1" will have the same ID than the input inside "Form2". How can I identify the text inside every input?
I mean, maybe exist something like: form1.getelementbyid(input_value)?
What I need to do is to execute a function to calculate a result for every form, this is why I need to recognize the inputs for every form.
This is the code which I have for execute a function and get the results for one form, it works fine:
function Calcular_Montos()
{
var val = $('#IBC').val();
var porcentaje_riesgos = $('[name=porcentaje_riesgos]:checked').val();
var exento_salud = $('[name=exento_salud]:checked').val();
$.ajax({
url: 'costo_empleado.php',
type: 'POST',
data: {"IBC": val, "porcentaje_riesgos": porcentaje_riesgos, "exento_salud": exento_salud},
success: function (response)
{
$('#resultado').html(response);
}
});
}
But as you can see, those #IBC, #porcentaje_riesgos, #exento_salud are IDs which are going to be common for Form1 and Form2
Give separate id to form 1 and form 2 and use descendent operator (>) to select the respective inputs inside the forms
$(' #form1 > #IBC')
function Calcular_Montos()
{
var val = $('#form1 > #IBC').val();
var porcentaje_riesgos = $('[name=porcentaje_riesgos]:checked').val();
var exento_salud = $('#form1 > [name=exento_salud]:checked').val();
$.ajax({
url: 'costo_empleado.php',
type: 'POST',
data: {"IBC": val, "porcentaje_riesgos": porcentaje_riesgos, "exento_salud": exento_salud},
success: function (response)
{
$('#resultado').html(response);
}
});
}
I'm trying to pass a boolean (checked/unchecked) value with .ajax, and I can't make it work. I have read a bunch about how to get the value of a checkbox using .is(':checked'), vs .prop('checked') but I can't seem to make anything work.
Here is my HTML:
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
And here is my JavaScript
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $('checkbox#typeOfSearch').prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
I can make the script work for the select boxes, and those continue to work after I add the checkbox, but the value of the checkbox is not being passed.
All I am interested in is passing 'checked' vs 'unchecked'.
Any help would be appreciated. Thanks.
You are using invalid selector. Use input instead.
Your HTML have input element,
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
function send() {
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $('input#typeOfSearch').prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
}
$('#submit').click(function() {
send();
});
You can't select a checkbox as no such tag exists. Try input or even giving it a unique id without caring about the tag e.g. $('#typeOfSearch'):
function send() {
$cb = $('input#typeOfSearch');
console.log($cb.prop('checked'));
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $cb.prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
}
$('#submit').click(function() {
send();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
<button id="submit">Send</button>
Hope this helps :)
$(document).ready(function() {
//set initial state.
$('#typeOfSearch').change(function() {
$('#typeSelected').html(($(this).is(':checked') ? "TRUE" : "FALSE"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="typeOfSearch" /> This Type
<br>
Type Selected:
<span id="typeSelected">FALSE</span>
Your selector is wrong
$('checkbox#typeOfSearch')
You are looking for this:
<checkbox id="typeOfSearch">
If you just select by the id, it would work
$('#typeOfSearch')
The below are some of the ways you can see if the checkbox is checked. If the checkbox is checked the value is true or else it is false.
if ($('#typeOfSearch:checked').length > 0) {
/* Do something */
}
if($('#typeOfSearch').prop('checked') == true) {
/* Do something */
}
if ($('#typeOfSearch').filter(':checked')) {
/* Do something */
}
Hope this helps.
Please search better when asking Stack Overflow questions. This was the top hit on Google for "jquery get checked or unchecked":
https://stackoverflow.com/a/27265333/5129424
Your selector will only attach event to element which are selected in the beginning. You need to determine check unchecked state when value is changed:
$("#countries input:checkbox").change(function() {
var ischecked= $(this).is(':checked');
if(!ischecked)
alert('uncheckd ' + $(this).val());
});
Working Demo
What i have is a div with text inputs. What i want to do is send the div's HTML code to the server to be used on another page like so:
$.ajax({
url: 'process.php',
type: 'POST',
data: {
html: $("#form").html()
},
success: function (data) {
}
});
The thing is, if a user types in some data into the text inputs, that data is lost since its not part of the HTML. Is there a way i can force this data into the HTML? eg by using javascript to edit each input's value attribute?
Thanks in advance
Try the input event:
$(document).on('input', 'input.your_input', function() {
var that = $(this);
that.attr('value', that.val());
});
Inspect the input element and try type something:
$(document).on('input', '#textInp', function() {
var that = $(this);
that.attr('value', that.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="textInp" />
You can try sending the input values via parameters in the ajax function.
Try to run this snippet before making the call,
$("#form :text").attr("value",funcion(){
return $(this).val();
});
Instead of binding change event to all the input elements initially you can add the attribute before sending them to server.
You can try like this:
$("input").on('change', function() {
$(this).attr('value', $(this).val());
});
I am trying to replace Typeahead enabled input field value using jQuery. But after replacing the value when I click on the input field then it changed the value to original selected value.
If I select "US - DC" then using jQuery it display "US".
If I click on the input field then it replace the value "US" with the value "US - DC"!
I am using following code-
$("#country-id").bind("change", function(e){
var country = $(this).val();
var t = $(this);
$.ajax({
url: './state',
type: 'post',
data: 'id='+country,
cache: false,
dataType:'json',
success: function(data) {
var countryVal = country.split("-",1);
console.log(countryVal);
t.val(countryVal);
}
})
});
Thanks in advance.
Do you mean something like this?
jQuery("#btnClick").on("click", function(){
var countryVal = jQuery("#testInp").val().split("-", 1);
console.log(countryVal);
jQuery("#testResult").val(countryVal);
});
You can check this in jsfiddle ->
http://jsfiddle.net/ChoHongRae/zvkkb5fr/1/
Try to use $("#country-id").typeahead('val', countryVal) instead of t.val(countryVal) as long as "country-id" is the id of the typeahead bounded input.
<form method="POST" action="" id ="formaclient" >
<input name="fullname">
<input name="fullname1">
<input name="fullname2">
<input name="fullname3">
<input class="btn-update">
</form>
$(".btn-update").click(function (ev) {
ev.preventDefault();
var data = $(this).find("#formaclient").serialize();
console.log(data);
$.ajax({
type: 'POST',
url: 'demo/client_view_search_content.php',
data: $("#formaclient").serialize(),
success: function () {
alert('Success!')
},
error: function () {
alert('Failure!')
}
});
return false;
});
Something is wrong with
var data = $(this).find("#formaclient").serialize();
I'm not getting data, how to change var data = $(this).find("#formaclient").serialize(); that I will get data from form ?
Use closest() instead of find(). find() will check for the children only. While closest() will check for the parents
var data = $(this).closest("#formaclient").serialize();
Since the id is unique, you can directly get the form like this,
var data = $("#formaclient").serialize();
If you have multiple forms, use like this
var data = $(this).closest("form").serialize();
I think you are using .find() wrong, because .find() searches for element descendants(children).
I think you should use $("form#formaclient").serialize() in order to serialize data.
You are using this which is pointed to the .btn-update object. using .find() will check for the children of object only. use below to serialize the data :
var data = $("#formaclient").serialize();
.find() descends from the current element. Obviously, since there are no elements within the button, you won't be able to find the form.
Since you have the id of the form, why don't you just use it to locate the form?
$('#formaclient').serialize(); will do the trick.
Also, remember that all IDs must be unique, so you should not worry about mixing up the forms.
You don't need to find elements with specific id values - a simple $('#formaclient') will do fine. It will also avoid the need to serialize the form data twice as your code attempts to do at present.
Your end result should look like this:
$(".btn-update").click(function(ev) {
ev.preventDefault();
var myData = $('#formaclient').serialize();
console.log(myData);
$.ajax({
type: 'POST',
url: 'demo/client_view_search_content.php',
data: myData,
success: function () {
alert('Success!')
},
error: function () {
alert('Failure!')
}
});
return false;
});
As others have pointed out, trying to find an element will only search descendant elements from the one you start from (the button in your case).