good day to all, i have this script where i am appending checkbox when the add button is click. now my problem is that when i add two checkbox, when i click the second checkbox it triggers the first checkbox not the second checkbox.
here's my code.
$(document).ready(function () {
var TempCounter = parseInt($('input[name^="TempID"]').val());
var count = TempCounter;
var ajaxCount = count + 1;
var reqCount = TempCounter;
$('#addButton').click(function(e) {
$("#ApprovalRequestor").append('<div><input style="margin-left:20px;" type="checkbox" id="requestorManagerChecked'+count+'" name="requestorManager['+count+']" > </input>'
+ '<span>'+document.getElementById(document.getElementById('selectOtherRequestor').value).innerHTML+'</span>Delete <input type="hidden" value="'+$('#selectOtherRequestor').val()+'" id="ApproversID" name="ApproversID['+count+']"> </input>'
+ '<input type="hidden" id="TempCount" name="TempCount" value="'+count+'"/>'
+ '<input type="hidden" id="levelID" name="levelID['+count+']" value="1"> </input> </div>');
$('#requestorManagerChecked'+count+' ').change(function() {
if($('#requestorManagerChecked'+reqCount+' ').is(":checked") ) {
$('#requestorManagerChecked'+reqCount+' ').val(1);
alert('requestorManagerChecked'+reqCount+' ');
alert($('#requestorManagerChecked'+reqCount+' ').val() );
}
else {
$('#requestorManagerChecked'+reqCount+' ').val(0);
alert($('#requestorManagerChecked'+reqCount+' ').val() );
}
});
$.ajax({
type: 'post',
url: 'mis.php/fileApproversListController/getCounter',
data: 'variable='+ajaxCount,
success: function(data) {
$('#Count').html(data);
}
});
reqCount = count;
ajaxCount++;
count++;
});
here's my controller
function SaveApprovers() {
$this->load->model('new_development_model');
$requestType = $this->input->post('requestTypeID');
$ApproversLists = $this->input->get_post('Approvers');
for($ctr = 0; $ctr <= $this->input->get_post('counter'); $ctr++) {
$ApproversLists[$ctr]['ApproversLevel'];
$ApproversLists[$ctr]['Required'];
$ApproversLists[$ctr]['ApproversID'];
$Remark = $this->input->get_post('Remarks');
$this->new_development_model->ApproversList($ApproversLists[$ctr]['ApproversLevel'], $ApproversLists[$ctr]['Required'],$ApproversLists[$ctr]['ApproversID'],$Remark);
}
}
Related
my autoincrement is not working on my appended textbox.
My target is to have an auto-increment in my appended textbox. I have tried several ways and one of my way is:
var count = 1; then an input type value='"+ count +"'
But it is still not working. Is there anything i missed? Thank you in advance
This is a screenshot of my work:
html:
<div id="result"> </div>
script:
let ajaxResult = []; // the pushed data will be saved here
let save_method;
let table;
let base_url = "<?php echo base_url();?>";
let result = [];
var html = "";
function removeDuplicates(result) {
return Object.values(result.reduce((acc, curr) => {
acc[curr.player] = acc[curr.player] || curr;
return acc;
}, {}))
}
const combine = (source) => {
return source.reduce((acc, curr) => {
if (acc[curr.weight]) {
const levelArr = acc[curr.weight];
const last = levelArr[levelArr.length - 1];
if (last.length === 2) {
levelArr.push([curr])
} else {
last.push(curr)
}
} else {
acc[curr.weight] = [
[curr]
];
}
return acc;
}, {})
};
const uniquePlayers = removeDuplicates(result);
$(document).ready(function () {
var eventID = $('#eventsssiud').val();
//datatables
table = $("#entry_list1").DataTable({
processing: false,
serverSide: true,
order: [],
searching: false,
paging: false,
info: false,
ajax: {
url: "<?php echo site_url('entry/ajax_list')?>",
type: "POST",
async: true,
dataType: "json",
data: { eventID: eventID },
success: function (data) {
result = combine(removeDuplicates(data.data2));
console.log(result);
var keys = Object.keys(result)
for (var i = 0; i < keys.length; i++) {
result[keys[i]].forEach(function (val) {
var length_ = val.length;
val.forEach(function (value, index) {
var idaa = value.eventID;
var count = 1;
if (idaa == eventID) {
if (length_ == 2) {
var entryIDs = index == 0 ? "entryIDM[]" : "entryIDW[]"
var players = index == 0 ? "playerM[]" : "playerW[]"
var weights = index == 0 ? "weightM[]" : "weightW[]"
var lightBands = index == 0 ? "lightBandM[]" : "lightBandW[]"
html += `<input type="text" name="${entryIDs}" value="${value.entryID}">
<input type="text" name="${players}" value="${value.player}">
<input type="text" name="${weights}" value="${value.weight}">
<input type="text" name="${lightBands}" value="${value.lightBand}">
<input type="text" name="eventID" value="${value.eventID}">
<input type="text" class="something" name="something" value='"+ count + "' name='photo_" + (count++) +"'> // The autoincrement does not work here.`
}
}
})
})
}
document.getElementById("result").innerHTML = html //add html to div
},
},
"columnDefs": [{
"targets": [0], //first column
"orderable": false, //set not orderable
},
{
"targets": [-1], //last column
"orderable": false, //set not orderable
},
],
});
});
You used + inside a template string which won't work the way you expected, instead use ${}.
html += `<input type="text" name="${entryIDs}" value="${value.entryID}">
<input type="text" name="${players}" value="${value.player}">
<input type="text" name="${weights}" value="${value.weight}">
<input type="text" name="${lightBands}" value="${value.lightBand}">
<input type="text" name="eventID" value="${value.eventID}">
<input type="text" class="something" name="something" value="${count}" name="photo_${count++}">`
On click of a button the code will check that "select all" is selected or individually selected. Now the problem is if one selects any "select all" checkbox and if then unchecked any option, then these unchecked values are passed instead of checked ones.
$("#next").click(function () {
debugger
$(".show").show();
$("#next").hide();
if ($('.checkbox2 ul.dropdown-content li input[type=checkbox]').first().is(':checked') == true){
$.each(budata, function (key, value) {
arr.push(key);
});
}else {
debugger
arr = $('option[name=BU]:checked').map(function () {
return this.value;
}).get();
}
var bu = arr.join(',');
HTML CODE
<div class="checkbox2">
<div class="input-field col s6">
<select id="dropdown1" multiple>
<option value="" disabled selected>Select BU</option>
</select>
<label>BU</label>
</div>
</div>
AJAX CALl for BU values(Checkbox values)
var data = {};
data.dateFrom = $("#dateFrom").val();
data.BU = $("#dropdown1").val();
data.Location = $("#Location").val();
data.Type = $("#dropdown").val();
$.ajax({
type: 'POST',
url: ServiceURL + 'MaterialClearance/getBU/',
async: false,
success: function (data) {
$('#dropdown1').html('<option id="selectall" name="selectall" value="selectall" ">(Select All)</option>');
if (data.length > 0) {
for (i = 0; i < data.length; i++) {
budata[data[i].BU] = 0;
$('#dropdown1').append('<option name="BU" value="' + data[i].BU + '">' + data[i].BU + '</option>')
}
}
$('#dropdown1').material_select();
}
});
CODE for select all nd individual checked checkbox
$('.checkbox2 ul.dropdown-content li').click(function () {
debugger
if ($('.checkbox2 ul.dropdown-content li').first().is(".selected")) {
$('.checkbox2 ul.dropdown-content li:not(:first-child)').each(function (index) {
$(this).find("input[type=checkbox]").prop("checked", $('.checkbox2 ul.dropdown-content li').first().find("input[type=checkbox]").prop("checked"));
});
}
else {
alert($('option[name=BU]:checked'));
$('.checkbox2 ul.dropdown-content li input[type=checkbox]').first().prop("checked", false);
alert($('option[name=BU]:checked'));
}
});
http://jsfiddle.net/R89fn/9/
If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?
$("#submit").click(function (event) {
var string = "tb";
var i;
for (i = 1; i <= count; i++) {
if (document.getElementById(string+1).value=="") {
event.preventDefault();
break;
}
}
});
The above code is what I am using to get the value from the text fields using there id
I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.
The code for the add button should use this,
var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);
Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/
var count = 0;
$(document).ready(function () {
$("#b1").click(function () {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function () {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function (event) {
var inputBoxes = $('#form').find('input[type="text"]');;
if (inputBoxes.length < 1) {
alert('No text inputs to submit');
return false;
} else {
inputBoxes.each(function(i, v) {
if ($(this).val() == "") {
alert('Input number ' + (i + 1) + ' is empty');
$(this).css('border-color', 'red');
}
});
alert('continue here');
return false;
}
});
});
<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
var count = 0;
$(document).ready(function() {
$("#b1").click(function() {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function() {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function(event) {
var string = "#texttb";
var i;
for (i = 1; i <= count; i++) {
if ($('input[type = text]').val() == "") {
event.preventDefault();
break;
}
}
});
});
</script>
<style>
.newTextBox
{
margin: 5px;z
}
</style>
Reason:
you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement.
If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:
<input type="text" required />
I'm looking for jQuery code which will list all classess from inputs and display how many times every class (in this case class=value) is selected.
html schema:
<input type="checkbox" name="t1" class="a1" value="a1">
<input type="checkbox" name="t1" class="a2" value="a2">
<input type="checkbox" name="t1" class="a3" value="a3">
<input type="checkbox" name="t2" class="a1" value="a1">
<input type="checkbox" name="t2" class="a2" value="a2">
<input type="checkbox" name="t2" class="a3" value="a3">
...
<input type="checkbox" name="t9" class="a99" value="a99">
example of expected result:
a1 - 2
a2 - 0
a3 - 0
a99 - 0
Try
var map = {};
$('input[type=checkbox]').each(function () {
if (this.checked) {
map[this.className] = (map[this.className] || 0) + 1;
} else {
map[this.className] = map[this.className] || 0;
}
});
console.log(map)
Demo: Fiddle
You could try something like this:
var checked = new Array();
$("input[type=checkbox]").each( function() {
var cl = $(this).attr('class');
if (typeof(checked[cl]) == "undefined") checked[cl] = 0;
if ($(this).is(':checked')) checked[cl]++;
});
After this, you will have variable checked containing all checkbox classes, with number of checked boxes for each class.
Let me know if this works for you.
Fiddle: http://jsfiddle.net/smBSw/1/
var resultList = {}
$('input:checkbox').each(function () {
var result = resultList[this.className] || 0;
if (this.checked) {
result++;
}
resultList[this.className] = result;
});
console.log(resultList)
console.log(JSON.stringify(resultList));
You can use like :
var className = [];
$("#btn").click(function () {
$("#result").html("");
$("input[class^=a]").each(function () {
className.push($(this).attr("class"));
});
className = jQuery.unique(className);
for (i = 0; i < className.length; i++) {
var count = 0;
$("." + className[i]).each(function () {
if (this.checked) {
count++;
}
});
$("#result").append(
"<br/><span> " +
"className: " + className[i] + ", " +
"count :" + count +
"</span>"
);
}
});
demo fiddle
Basically you will need to iterate through these inputs.. but you will need a place to save the counts
$(".checkboxes").on("change", "input", function() {
var results = {"a1": 0, "a2": 0, "a3": 0};
$(".checkboxes input").each(function(i, checkbox) {
if (!$(checkbox).prop("checked")) {
return;
}
results[$(checkbox).val()] = results[$(checkbox).val()] + 1;
});
var resultsToAppend = '';
$.each(results, function(key, value) {
resultsToAppend += '<li>' + key + ' : ' + value + '</li>';
});
$(".results").html(resultsToAppend);
});
Here's a fiddle
when i have to open this page i want to display all contacts in phone with out click on any button.
Here myFunction() displays all contacts.
I have to call `myFunction()`, in this code. I dont know where to call this function. Help me
var ar1 = new Array;
var ar2 = new Array;
var name, number;
var counter = 1;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
filter = [ "displayName", "phoneNumbers" ];
navigator.contacts.find(filter, onSuccess, onError, options);
}
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
name = contacts[i].displayName;
number = contacts[i].phoneNumbers[j].value;
ar1.push(name);
ar2.push(number);
// here i called myFunction(), but it's displaying one contact in multiple times
}
// here i called myFunction(), but it's displaying one contact in multiple times
}
// Here i called myFunction(), the function is not calling
}
function onError(contactError) {
alert('onError!');
}
// where to call this function
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
</script>
</head>
<body>
</br>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />selectAll</br> <br />
<br /> <br />
</div>
</div>
</body>
</html>
I cannot catch what you want exactly.
if you want to generating phonenumber checkbox list when your app starts,
just call myFunction() in end of onSuccess() callback.
if you want another time, you should define a event handler that you want like below.
$("#PhonenumberListButton" ).click( function() { myFunction(); } );
and your code can occur index exception during loop.
Let's think about below.
each contact has 1 name but has 1 or more phone numbers
your code pushes each name into ar1 and also pushes each phone numbers of contact into ar2
so ar2.length can be greater than ar1.length
your generating display code use ar2.length for loop. it should make exception if any contact has 2 or more phonenumbers.
This's a reason of stop your loop in onSuccess().
Fixed Code
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
name = contacts[i].displayName;
ar1.push(name);
ar2[i] = []; // array for multiple phone#.
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
number = contacts[i].phoneNumbers[j].value;
ar2[i].push(number);
}
}
myFunction(); // display phone numbers
}
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
if ( ar2[i].length ) { // avoid none phone# exception
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i][0] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
}