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++}">`
Related
I have an image gallery with search input , where the user can type image title or image tag and search for matches. I now need to be able to have multiple search for the tags. For example if i type : #tree - > the result will be all the images that have "tree" in their tags (specifically ) , not the ones that partially contains the word, as Tag search should be specific. I need to be able to type : #tree,#sky - > and the output to be all the images that have "tree" and "sky" in them . So far my code executes only the first example .
HTML :
<div class="searchBtn">
<input type="text" id="inputValue" placeholder="Search by name or #tag">
<button onclick="Search()" type="button">Search</button>
</div>
JS:
let filterSearch = $("#inputValue").val().toLowerCase();
function findAllImages(filter, start, itemsCount) {
let photos = [];
let tagSign = "#";
const searchByTag = filterSearch [0] === tagSign;
let searchCondition = searchByTag ? filterSearch.slice(1) : filter;
let newFiltered = imageArrayPhotos.filter(
searchByTag ? image => image.tag.indexOf(searchCondition) >= 0 :
image => image.title.toLowerCase().indexOf(searchCondition) >= 0);
for (let i = start; i < newFiltered.length; i++) {
photos .push(newFiltered [i]);
if (photos.length >= numberOfImages) {
break;
}
}
return photos ;
}
Can i do it with a callback function on let newFiltered = imageArrayPhotos.filter(function() {}) that goes through all the possibilities?
Why don't you use the regex. check if this is feasible.
let searchByTag = true;
let imageArrayPhotos = [{
tag: 'tree',
title: 'tree'
},
{
tag: 'forest',
title: 'tree'
},
{
tag: 'sky',
title: 'sky'
},
{
tag: 'bird',
title: 'bird'
},
{
tag: 'watertree',
title: 'sky'
},
];
let filterSearch = '';
let searchCondition = '';
let pattern;
let newFiltered = [];
function Search() {
newFiltered = [];
filterSearch = '';
searchCondition = '';
filterSearch = $("#inputValue").val();
filterSearch = filterSearch.split(',');
//searchCondition = searchByTag ? filterSearch.slice(1) : filter;
//newFiltered = imageArrayPhotos.filter(checkFilter);
filterSearch.forEach(function(item) {
item = $.trim(item);
searchByTag = item[0] == "#";
pattern = new RegExp("^" + $.trim(item).replace(/#/g, '') + "$");
let itemData = imageArrayPhotos.filter(checkFilter);
if (itemData.length > 0) {
newFiltered = newFiltered.concat(itemData);
}
});
console.log(newFiltered);
}
function checkFilter(image) {
return searchByTag ? pattern.test(image.tag) :
pattern.test(image.title)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="searchBtn">
<input type="text" id="inputValue" placeholder="Search by name or #tag">
<button onclick="Search()" type="button">Search</button>
</div>
I'm new to JS
I currently have two functions.
The both work as they should.
However, I cannot use the value from the first document function and fire the onchange event in the second and use the selected value.
I would like the selected value from the first script to fire the onchange event in the second script.
Please help!
Html:
<td>
<input type="text" name="product[]" placeholder="Product"
class="product"
onfocus="javascript:$(this).autocomplete('search','');">
</td>
1: Auto complete:
$(function () {
var validOptions = <? echo $get_product_names ?>;
previousValue = "";
$(".product")
.autocomplete({
source: validOptions,
select: function( event, ui ) {alert($(this).val())},
minLength: 0
}).keyup(function () {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
}).click(function () {
$(this).autocomplete('search', $(this).val())
});
});
2nd: Generate Pricing:
$(document).on('change', '.product, .width, .drop', function () {
var product = $(".product", $(this).parent().parent()).val();
//alert(product);
var width = $(".width", $(this).parent().parent()).val();
var drop = $(".drop", $(this).parent().parent()).val();
var sub_total = $(".total", $(this).parent().parent());
if (product === "" || width === "" || drop === "") {
var parent = sub_total.val(0);
}
if (product !== "" && width !== "" && drop !== "") {
$.ajax({
url: "#",
method: "POST",
data: {
"product": product,
"width": width,
"drop": drop
},
success: function (data) {
if (data === "") {
var parent = sub_total.val(0);
}
else {
var parent = sub_total.val(data);
}
calculate(parent);
}
});
}
});
For future readers:
I switched over to chosen
My code looks like this now.
<td>
<select data-placeholder="Choose Type" name="product[]"
class="product chosen-select" tabindex="2"
style="width: 150px">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
js:
//trigger product change
$('.product').click(function () {
$('.product').trigger("chosen:updated");
});
$(document).on('change', '.product, .width, .drop', function () {
var product = $(".product", $(this).parent().parent()).val();
//alert(product);
var width = $(".width", $(this).parent().parent()).val();
var drop = $(".drop", $(this).parent().parent()).val();
var sub_total = $(".total", $(this).parent().parent());
if (product === "" || width === "" || drop === "") {
var parent = sub_total.val(0);
}
if (product !== "" && width !== "" && drop !== "") {
$.ajax({
url: "#",
method: "POST",
data: {
"product": product,
"width": width,
"drop": drop
},
success: function (data) {
if (data === "") {
var parent = sub_total.val(0);
}
else {
var parent = sub_total.val(data);
}
calculate(parent);
}
});
}
});
I have used a input like that:
<input type="text" onkeypress="maskDexxtz(this,maskCPF)" maxlength='14' title="<?php echo $this->__('Tax/VAT number') ?>"/>
I want to format input when customer type as: xxx.xxx.xxx-xx
My js code:
<script type="text/javascript">
function maskCPF(v) {
v = v.replace(/\D/g, "");
v = v.replace(/(\d{3})|(\.{1}d{3})/g, "$1.$2");
return v;
}
function maskDexxtz(o, f) {
v_obj = o
v_fun = f
setTimeout('mask()', 1)
}
function mask() {
v_obj.value = v_fun(v_obj.value)
}
</script>
However I just make it as xxx.xxx.xxx but can't capture two last key -xx.
Anywho can help me for it?
Here is a working version. I don't think there is a way to do this with regex replace.
$('input').on('keypress', (e, el) => {
mask(e.currentTarget);
})
function mask(el) {
timeout = setTimeout(() => {
el.value = el.value.replace(/\D/g, "");
let parts = el.value.match(/(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,2})?/);
el.value = '';
for(let i = 1; i <= 4; i++) {
if(parts[i] !== undefined) {
el.value += parts[i];
if(parts[i+1] !== undefined) {
el.value += i < 3 ? '.' : '';
el.value += i == 3 ? '-' : '';
}
}
}
}, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeypress="" maxlength='14' title="Tax/VAT number"/>
If I have the following HTML on a page:
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
I would like to select the items using JavaScript (or JQuery) in such a way that I can loop over the items using the outer array.
Currently I have the following JQuery/JavaScript to handle the items:
var items = ($('[name*="item["]'));
var i = 0;
while (i < items.length) {
if (items[i++].value === '') {
// No ID set.
}
else if (items[i++].value === '') {
// No title set.
}
else if (items[i++].value === '') {
// No description set.
}
}
Is there a way to select the elements so that I can loop over them using notation more like the following (Where items.length is 3)?
for (var i = 0; i < items.length; i++) {
if (items[i][0].value === '') {
// No ID set.
}
else if (items[i][1].value === '') {
// No title set.
}
else if (items[i][2].value === '') {
// No description set.
}
}
Or even more like this?
for (var i = 0; i < items.length; i++) {
if (items[i].id.value === '') {
// No ID set.
}
else if (items[i].title.value === '') {
// No title set.
}
else if (items[i].description.value === '') {
// No description set.
}
}
Or would this require more manipulation and processing to go from selecting from the DOM to creating the data structure to loop over?
I think this is exactly what you are looking for (which is not really related to selectors):
function serialize () {
var serialized = {};
$("[name]").each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for(var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if(!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if(i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if(i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
}
console.log(serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
See the related JSFiddle sample.
Here's a way to add a custom function into JQuery to get the data structure you're looking for.
$.fn.getMultiArray = function() {
var $items = [];
var index = 0;
$(this).each(function() {
var $this = $(this);
if ($this.attr('name').indexOf('item[' + index + ']') !== 0)
index++;
if (!$items[index])
$items[index] = {};
var key = $this.attr('name').replace('item[' + index + '][', '').replace(']', '');
$items[index][key] = $this;
});
return $items;
};
var $items = $('input[name^="item["]').getMultiArray();
This allows you to have the references in your "ideal" example.
var $items = $('input[name^="item["]').getMultiArray();
$items[0].id;
JS Fiddle: https://jsfiddle.net/apphffus/
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);
}
}