checkbox checked when value same with data from database-javascript - javascript

hi everyone please help,
i'm new in javascript, i have checkbox with random value, so i want to when there is data from database same with value in checkbox, checkbox will checked,
this is my checkbox,
#foreach ($loin as $loin)
<div class="custom-control custom-checkbox">
<input class="custom-control-input loincode" type="checkbox" id="{{$loin->sap_code}}" name="sap_code[]"
value="{{$loin->sap_code}}">
<label for="{{$loin->sap_code}}" class="custom-control-label">{{$loin->sap_code}}
</label>
</div>
#endforeach
and this my js
$('.tampilModalUbahPts').on('click',function () {
var id = $(this).data('id');
$('.modal-body form').attr('action','/pts/'+id+'/update');
$.ajax({
url: '/ptspt/getubah',
data: {id : id},
method:'get',
dataType : 'json',
success: function (data) {
$('#lbs').val(data.lbs);
$('.loincode').attr("checked",data.loin== value);
}
});
});
sorry for bad english.

then use this
$('.loincode').each(function( index ) {
$(this).attr("checked",(data.loin && data.loin.filter(x=>(x==$(this).val())).length) ? true : false);
});
var data={loin:["108591","108592"]}
$('.loincode').each(function( index ) {
$(this).attr("checked",(data.loin && data.loin.filter(x=>(x==$(this).val())).length) ? true : false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="loincode" value="108591" />
<input type="checkbox" class="loincode" value="108592" />
<input type="checkbox" class="loincode" value="108593" />

Related

jquery add / remove item from array

I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
if ($(this).attr("id") == 'price') {
if (this.checked) {
priceArray.push($(this).val());
}
else {
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
}
}
});
});
Adding the value to the array works perfectly, however removing items results in this error:
Cannot read property 'toLowerCase' of undefined
on this line:
return value != $(this).val();
Run the code snippet and check
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
$(this).change(function () {
if (this.checked) {
priceArray.push($(this).val());
$("#displayarray").html("array=[" + priceArray+"]");
}
else {
var index = priceArray.indexOf($(this).val());
if (index > -1) {
priceArray.splice(index, 1);
}
$("#displayarray").html("array=[" + priceArray+"]");
}
});
});
});
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>
Replace
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
By
val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
return value != val;
});
Don't forget the scope where your are in the callback function.
You can try using filter instead of $.grep:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
values.push($this.val());
}
else
{
values = values.filter(x => x != $this.val());
}
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
Use this method:
$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...
This will work even if checkbox is dynamically added.
You could do this very cleanly with a functional style
<div class="checkboxes">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
</div>
And
(function() {
$(".checkboxes input[type=checkbox]").on("click", function() {
var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
return parseFloat(b.value);
}).toArray();
console.log(x)
});
})();
I had a similar situation and I was able to overcome it in the following way :
My jQuery :
$(document).ready(function(){
$("#dataFilterForm").on("input", function() {
var values = '';
var boxes = $('input[name=vehicle]:checked');
boxes.each(function(b){
values = values + boxes[b].id + ', ';
});
$('#filterResult').text(values.substring(0, values.length-2));
});
});
My HTML :
<form id="dataFilterForm">
<input type="checkbox" id="Filter1" name="vehicle" value="Bike">
<label for="Filter1">Filter1</label><br>
<input type="checkbox" id="Filter2" name="vehicle" value="Car">
<label for="Filter2">Filter2</label><br>
<input type="checkbox" id="Filter3" name="vehicle" value="Boat">
<label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>

Unable to create array for checkboxes with jquery AJAX PHP

I am close but missing something. Im trying to pass variables of multiple checkboxes to a php page with jquery. My code:
<div id="students">
<div class="field">
<label>
<input type="checkbox" name="pupil[a]" value="a" id="pupil"/>
Pupil A
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[b]" value="b" id="pupil"/>
Pupil B
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[c]" value="c" id="pupil"/>
Pupil C
</label>
</div>
</div>
<br /><br />
<div id="occupation">
<div class="field">
<label>
<input type="checkbox" name="occupation[Software]" value="Software" id="occupation"/>
Software
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[Marketing]" value="Marketing" id="occupation"/>
Marketing
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[Teacher]" value="Teacher" id="occupation"/>
Teacher
</label>
</div>
</div>
My jquery:
$(document).ready(function(){
$(":checkbox").on('change', function() {
var val = [];
var myval = []; //defining to pass with AJAX
var theval =[]; //defining to pass with AJAX
$(':checkbox:checked').each(function(i){
myval[i] = $(this).attr('id');
theval[i] = $(this).attr('name');
var newval = myval[i] +"="+ myval[i];
$.ajax({
type: "POST",
url: 'draftdata.php',
data : { newval}, //tried this and
data : {myval : theval}, // and tried this too
success: function(data){
$("#result").html(data);
}
});
});
});
});
I only want to pass the data that was checked in the checkboxes to php. There may be multiple group of checkboxes so the $_POST['desiredValue'] cannot be defined. So I can only check if its set by if(isset($_POST['desiredValue'])).
When I check Software, Marketing and Teacher and on draftdata.php do a print_r($_POST[]),I get:
Array
(
[myval] => Array
(
[0] => Software
[1] => Marketing
[2] => Teacher
)
)
What i want to get is:
Array
(
[0] => 'occupation' = 'Software'
[1] => 'occupation' = 'Marketing'
[2] => 'occupation' = 'Teacher'
)
What am I missing?
Thanks.
I modified your html code in this way,
<form id="myform" class="" action="draftdata.php" method="post">
<div id="students">
<div class="field">
<label>
<input type="checkbox" name="pupil[]" value="a" id="pupil" /> Pupil A
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[]" value="b" id="pupil" /> Pupil B
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="pupil[]" value="c" id="pupil" /> Pupil C
</label>
</div>
</div>
<br />
<br />
<div id="occupation">
<div class="field">
<label>
<input type="checkbox" name="occupation[]" value="Software" id="occupation" /> Software
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[]" value="Marketing" id="occupation" /> Marketing
</label>
</div>
<div class="field">
<label>
<input type="checkbox" name="occupation[]" value="Teacher" id="occupation" /> Teacher
</label>
</div>
</div>
<button type="button" name="button" id="fsubmit">Submit</button>
</form>
by adding a form and
<button type="button" name="button" id="fsubmit">Submit</button>
and then using the id of the button #fsubmit into our jquery.
<script type="text/javascript">
$(document).ready(function() {
$("#fsubmit").click(function(e) {
var val = [];
var id = []; //defining to pass with AJAX
var name = []; //defining to pass with AJAX
var val = [];
$('input:checkbox:checked').each(function(i, v){
id[i] = $(this).attr('id');
name[i] = $(this).attr('name');
val[i] = $(this).val();
});
var url = $('#myform').attr('action');
$.ajax({
url: url,
type: "POST",
dataType: 'json',
data : {
'id': id,
'name': name,
'val': val
},
success: function(data) {
// $("#result").html(data);
console.log(data);
}
});
});
});
</script>
notice that I change some of the variable, change this according to your needs,
var val = [];
var id = []; //defining to pass with AJAX
var name = []; //defining to pass with AJAX
var val = [];
and also added with this
var url = $('#myform').attr('action');
and, dataType: 'json',
what the jquery do, when the user click on the button, get the link from the form action and look for the checked values and sent it to the php.
here the sample of the php
<?php
if ( isset($_POST['id']) ) {
$temp['id'] = $_POST['id'];
}
if ( isset($_POST['name']) ) {
$temp['name'] = $_POST['name'];
}
if ( isset($_POST['val']) ) {
$temp['val'] = $_POST['val'];
}
$data['data'] = $temp;
echo json_encode($data);
check your log for the result,
hope this help

Get the radio button value through ajax to php file

After clicking the radio button, the value from the radio button is not being passed when the onclick event is triggered. Here is my code:
<form name="Form1" id="color" style="font-size: 100%" action="#">
<input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="blue"/>Blue <br /></p>
<p> <input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="red"/>Red
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function MyAlert() {
var radio1=$('input[type="radio"]:checked').val();
var pass_data = {
'radio1' : radio1,
};
alert(pass_data);
$.ajax({
url : "",
type : "POST",
data : pass_data,
success : function(data) {
}
});
return false;
}
</script>
<?php
echo $radio1=$_GET['radio1'];
?>
When I click the radio button, I get the error
Undefined index: radio1
I want to display value of the radio button when clicking it within the same page.
Firstly make ajax to separate PHP page where you will access the radio value. Also make alert after you receive the data.
$.ajax({
url : "post.php",
type : "POST",
data: pass_data,
success : function(data) {
// alert radio value here
alert(data);
}
});
Crete a separate PHP file post.php where you access radio input. Since you are making POST request you need to use $_POST instead of $_GET to get radio button value.
<?php
$radio1 = $_POST['radio1'];
echo $radio1;
?>
<input type="radio" id="status" name="status" value="1" /> Mbyllur<br />
<input type="radio" id="status" name="status" value="0" /> Hapur<br />
function MyAlert()
{
var radio1=$('input[type="radio"]:checked').val();
var pass_data = {
'radio1' : $('input[name=status]:checked').val(),
};
alert(pass_data);
$.ajax({
url : "",
type : "POST",
data : pass_data,
success : function(data) {
}
});
return false;
}
I would use a newer version of jquery .
You can't give two elements the same id.
I would rewrite the code as follow :
$(function() {
$(document).on('change', '[name="radio1"]' , function(){
var val = $('[name="radio1"]:checked').val();
alert(val);
/*
Ajax code 1 (GET) :
$.get('/myurl?val=' + val, function(){
});
Ajax code 2 (POST) :
$.post('/myurl', {val : val}, function(){
});
*/
});
});
<form name="Form1" id="color" style="font-size: 100%" action="#" >
<input type="radio" name="radio1" value="blue"/>Blue <br />
<p> <input type="radio" name="radio1" value="red"/>Red
</form>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
Try This -->
<form name="Form1" id="color" style="font-size: 100%" action="#" >
<input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="blue"/>Blue <br /></p>
<p> <input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="red"/>Red
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function MyAlert()
{
var radio1=$('input[type="radio"]:checked').val();
//alert(radio1);
var pass_data = {
'radio1' : radio1,
};
//alert(pass_data);
$.ajax({
url : "request.php", // create a new php page to handle ajax request
type : "POST",
data : pass_data,
success : function(data) {
}
});
return false;
}
</script>
request.php
<?php
if(isset($_POST['radio1']))
{
echo $radio1=$_POST['radio1'];
}
?>
Above code handle with ajax so, its not refresh the page.
<script>
$(document).ready(function() {
$("#Enviar").click(function (e) {
var cedula = document.getElementById("Cedula").value;
var Nombre = document.getElementById("Nombre").value;
var Apellido = document.getElementById("Apellido").value;
var Sexo = $('input:radio[name=SexoC]:checked').val();
var Edad = document.getElementById("Edad").value;
var FechaN = document.getElementById("date").value;
var Tele = document.getElementById("tel").value;
var Direccion = document.getElementById("Direccion").value;
var Invitacion = document.getElementById("Invitacion").value;
var CasaG = document.getElementById("CasaG").value;
var Rango = document.getElementById("Rango").value;
var cadena = "Cedula="+cedula+"&Nombre="+Nombre+"&Apellido="+Apellido+"&Sexo="+Sexo+"&Edad="+Edad+"&Fecha="+FechaN+"&Tele="+Tele+"&Direccion="+Direccion+"&Invitacion="+Invitacion+"&CasaG="+CasaG+"&Rango="+Rango;
$.ajax({
type:'POST',
url:'datos/Registrar.php',
data: cadena,
beforeSend: function(){
console.log(cadena);
},
success:function(Resp){
alert(Resp);
}
});
return false;
});
});
</script>

Calling a function from a function using jquery and javascript

I have a dropdown and some radio buttons on a page. Everytime my user selects an item on the dropdownbox
and the radio buttons are checked, I want the checked values of the radio buttons to be cleared.
So I am calling a function in a change function but the radio buttons are not getting cleared.
please do you have an idea of what am doing wrong?
$('#ddlCustomerNumber').change(function () {
ClearFromOnDropDownChange();
$.ajax({
url: '#Url.Action("PopulateTextBoxes", "Home")',
type: "GET",
data: {
"customerId": $(this).val(),
"Country": $("#divcountry").text().trim()
},
success: function (data) {
if (data != null) {
var vdata = data;
for (var x = 0; x < data.length; x++) {
$("#Csr").val(data[x].Csr);
$("#CustomerName").val(data[x].CustomerName);
$("#Address").val(data[x].Address);
$("#TelePhone").val(data[x].Telephone);
$("#Contact").val(data[x].Contact);
$("#AccountListId").val(data[x].AccountListId);
}
}
}
});
});
function ClearFromODropDownChange() {
$("input:radio[name='1']:checked").val("");
$("input:radio[name='2']:checked").val("");
$("input:radio[name='3']:checked").val("");
$("#yoo").val("");
}
Here is the html
<ol id="RowTwoQuestions">
<li>
<span>Were Billing adjustments made?</span>
<input type="radio" name="1" value="Yes" id="g1yes" /><label for="g1yes">Yes</label>
<input type="radio" name="1" value="No" id="g1no" /><label for="g1no">No</label>
</li>
<li>
<span>Which direction was billing adjusted?</span>
<input type="radio" name="2" value="Up" id="g2up" /><label for="g2up">Up</label>
<input type="radio" name="2" value="Down" id="g2down" /><label for="g2down">Down</label>
</li>
<li>
<span>Was inventory returned?</span>
<input type="radio" name="3" value="Yes" id="g3yes" /><label for="g3yes">Yes</label>
<input type="radio" name="3" value="No" id="g3no" /><label for="g3no">No</label>
</li>
<li>
<span>Date customer inventory completed?</span>
#Html.TextBox("CustInventory", null, new { #id = "yoo", #class = "datepicker" })
</li>
</ol>
Take a look at worked Fiddle :
JS :
Replace :
function ClearFromODropDownChange() {
By :
function ClearFromOnDropDownChange() { // add the (n) to OnDrop
AND Replce :
$("input:radio[name='1']:checked").val("");
$("input:radio[name='2']:checked").val("");
$("input:radio[name='3']:checked").val("");
By :
$("input:radio[name='1']:checked").prop('checked', false);
$("input:radio[name='2']:checked").prop('checked', false);
$("input:radio[name='3']:checked").prop('checked', false);
Using jquery .prop() function to uncheck all checked inputs.
Hope that will help.

How to Hide a ID that incrments

So I'm trying to hide a ID tag that increments depending on how many input fields there are.
I included the HTML at the bottom for the input forms
The numbers at the end of deviceTemplate_(incremented numbers)
ex. deviceTemplate_1 is input field 1
deviceTemplate_2 is input field 2
$(function () {
// Other Code
// Trying to use this to hide fields
var fieldlistSelect = '#deviceTemplate_' + pliPosition;
//var $loader = $('section[role="main"]');
var $loader = form.parent();
//if this exists, then it will execute the following. It will check the whole HTML page.
$loader && $loader.showLoading();
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
dataType: 'html'
}).done(function(html) {
$loader && $loader.hideLoading();
$(fieldlistSelect).html(html);
$loader && $loader.hideLoading();
$(fieldlistSelect).html(html);
//Code I'm trying to get to work, not nessecary to use I'm just stuck
$('.vinCartApplyButton').click(function(ev) {
var aim = $(this);
var ap = aim.parent();
var newbk = ap.clone(true);
var apindex = $('[id^=deviceTemplate_]').index(ap);
var bkId = 'deviceTemplate_' + (apindex + 1);
newbk.addId('deviceTemplate_' + (apindex + 2));
ap.after(newbk);
});
//alert(html);
}).fail(function(jqXHR) {
//if this exists, then it will execute the following
$loader && $loader.hideLoading();
var html = jqXHR.responseText;
//alert(html);
});
});
});
<div class="vinCartFormStyling">
<form action="DeviceProcessing-AjaxValidate" method="post" onsubmit="return false;" id="deviceform1">
<fieldset id="deviceTemplate_1"><div class="vinBox">
<BR><div class="vinText"></div>
<BR><input type="text" onblur="convertCase(this)" name="DeviceId" maxlength="17" size="20"
value="" class="inputfield_en" />
</div>
</fieldset>
<input type="submit" class="device_form vinCartApplyButton" value="Apply">
<input type="hidden" name="Platform" value="ALP-HDD">
<input type="hidden" name="SKU" value="xxxxxxx">
<input type="hidden" name="Position" value="1">
<input type="hidden" name="PLIUUID" value="abcd1234" id="PLIUUID">
</form>
</div>

Categories

Resources