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);
}
});
}
Related
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 */);
});
In my code below, I'm pulling in data from SharePoint (basically an excel spreadsheet) and displaying on my page. Checkboxes are pushed to my page using .innerHTML and are given an ID programmatically.
My question: How can I determine whether those checkboxes are checked (being that they could be different each time my app loads) ?
(Once I know what is checked, I'll display more metadata on the next page based on the checks - that part I have figured out)
$.ajax({
url: "myWebsite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
You will need a way to know how many checkboxes has been created. When creating the checkboxes, them id must have a generic name and a number, for example id="checkbox0", id="checkbox1 and so on, then write the ammount of checkboxes in some part of the html code and put it some hidden tag. Then when reading the checkboxes data read the ammount of checkboxes and do a for
function getCheckboxes(){
var ammount = parseInt(document.getElementById("checkBoxesAmmount"));
var checkbox;
for(var i = 0; i<ammount; i++){
checkbox = document.getElementById("checkbox"+i);
//do staff
}
return;
I hope this works for you c:
This bit of jQuery returns all the checked input boxes that are in a ul with the class courseList:
jQuery('ul.courseList input:checked')
If your question is asked because the course name might change (your checkbox IDs are based on the course name), I suggest switching to the course number instead (or an appropriate mix of the two).
If you want to know if your dynamically created checkboxes were checked and want to do this via Javascript before the form is submitted, then add a class to your checkboxes (say dynamicCourse) and look for get the checked checkboxes via jQuery('input.dynamicCourse:checked').
Also, your checkboxes in your example don't have a value attribute set. If you're submitting it to a backend, you'll probably want it to have some value (course number would be my suggestion from the looks of it).
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).
I have the following Code
if($('#b_ID').length==1){
$('#gen, #dob').change(function(){
$.ajax({
type: "POST",
url: "<?=APP_PATH?>ajax/json.class.php",
data: {
gen: $('#gen').val()
,dob: $('#dob').val()
},
}).done(function( msg ) {
var wcs = $.parseJSON(msg);
console.log(wcs);
$('#b_ID').html('');
$('#b_ID').append('<option value="">'+'<?=_('[Select]')?>'+'</option>');
$.each(wcs, function(){
$wc=$(this);
//check for original value
var selected = $('#orig_ID').val()==$wc[0].ID_w?' selected="selected"':'';
$('#b_ID').append('<option '+selected+' value="'+$wc[0].ID_w+'">'+$wc[0].w_d+'</option>');
})
})
})
}
The above code is working perfect, if the form is loaded from other previous form. For example,
form1.php contains two fields
dob text input
select option
After we insert dob and select from option, when I save and then I load the second form which contains the select option that depends on those two inputs. For this purpose it works OK.
but what I need is I have all the elements on the form, all three fields, including one input and two select, so according to the first input of dob and the second select, I want to fill the third selection.
How could I change the above code to be able to work?