Array problems with Jquery - javascript

I have a Jquery code that is following:
var selectedQuestions = $("#SelectedQuestions");
var selectedCustomQuestions = $("#SelectedCustomQuestions");
var currentIds = new Array();
var currentText = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
var clickedId = $(this).attr("data-question-id");
currentIds.push(clickedId);
$('#CustomPickedTable tr').each(function () {
var ClickedText= $(this).find("td[data-attr-id]:first").html();
currentText.push(ClickedText);
});
});
selectedCustomQuestions.val(currentText.join("|"));
selectedQuestions.val(currentIds.join(","));
$("form").submit();
}
I have two types of TD in my table that is following:
<td data-question-id="7">test</td>
and
<td data-attr-id="5">test</td>
I want to be able to sort em into different hiddenfields these are my hiddenfields:
#Html.HiddenFor(model => model.SelectedCustomQuestions, new { #id = "SelectedCustomQuestions" })
#Html.HiddenFor(model => model.SelectedQuestions, new { #id = "SelectedQuestions" })
my Jquery code works when it comes to fill my array with CurrentIds but with currentText I get problems, if I have two <td data-attr-id="5">test</td> in my table they get duplicated in my array list and my array lenght is 7-10 which is weird. The CurrentText should only have 2 length and its not. How can I fix this?
Example on the problem.
I have this following inside my table:
<td data-attr-id="5">aaaa</td>
<td data-attr-id="5">ddd</td>
<td data-question-id="5">test</td>
<td data-question-id="15">test</td>
and this is what happens when i debug my jquery code
Thanks in advance!

Just try this one with slight modification.
var selectedQuestions = $("#SelectedQuestions");
var selectedCustomQuestions = $("#SelectedCustomQuestions");
var currentIds = new Array();
var currentText = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
var clickedId = $(this).attr("data-question-id");
currentIds.push(clickedId);
});
$('#CustomPickedTable td[data-attr-id]').each(function () {
var ClickedText = $(this).html();
currentText.push(ClickedText);
});
selectedCustomQuestions.val(currentText.join("|"));
selectedQuestions.val(currentIds.join(","));

You seem to be using "td[data-attr-id]:first" in your find selector, but you are "using data-attri-id" in your html, notice the added i.
edit :
You might also wanna use
var currentIds = [];
var currentText = [];
instead of :
var currentIds = new Array();
var currentText = new Array();
see:
What does [] mean in JavaScript?

Related

get innerHTML of the children of the currentTarget

I have this part of my html (more than one of same type):
<div class="this-product">
<img src="images/bag2.jpeg" alt="">
<span class="product-name">iPhone</span>
<span class="product-price">345445</span>
</div>
And this part of my javascript code meant to get the innerHTML of the span tags and assign them values as shown:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
var productName = document.getElementsByClassName('product-name')[0].innerHTML;
var productPrice = document.getElementsByClassName('product-price')[0].innerHTML;
var cartProductname = event.currentTarget.productName;
var cartProductprice = event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
Everything works well and every variable above has its value shown well apart from cartProductname and cartProductprice which display as undefined and also vscode tells me that productName is declared but not read. Where could I be wrong?
If I understand your question correctly, you could call querySelector on each product item element that you are iterating like so:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
// Update these two lines like so:
var productName = element.querySelector('.product-name').innerHTML;
var productPrice = element.querySelector('.product-price').innerHTML;
var cartProductname = productName; // event.currentTarget.productName;
var cartProductprice = productPrice; // event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
You can use event.currentTarget.querySelector('.product-name') to get element inside of another element

jQuery do not accept new fields in HTML

I try to create a generator for lucky numbers. I did it with C# and now with JavaScript and jQuery. You can see this here. When I add new field - JQ do not see it. Just try to click on numbers in "Your field". I have as standard 7 fields and they work fine but when I add new line script do not recognise it like something useful. Could you give me some advice?
change below js code. check this working plunker
Your code:
$('.spielzahlen').on('click', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
Change it with below code , there is only change in initialization other code are same :
$(document).on('click','.spielzahlen', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})

JQuery multiple input fields of each row keyup function not working

Hello I am trying to make my jquery code in working order but its not working at all, I don't know whats a problem behind it but it contains multiple text boxes in multiple rows, each row calculates its own sum
Here is Fiddle link
Here is my Code
$(document).ready(function(){
$('.employee input[type="text"]').keyup(function() {
var basic_salary = parseInt($('input[name^=txtMonthlyRate]').val());
var advance_salary = parseInt($('input[name^=txtAdvance]').val());
var recover_comm = parseInt($('input[name^=txtRecovery]').val());
var sales_comm = parseInt($('input[name^=txtSales]').val());
var deduction_salary = parseInt($('input[name^=txtDeduction]').val());
var adjustment_salary = parseInt($('input[name^=txtAdjustment]').val());
var total_sum = ((basic_salary+recover_comm+sales_comm) - (deduction_salary + advance_salary)) + adjustment_salary;
$('input[name^=txtTotal]').val(total_sum);
console.log(total_sum)
);
});
The txtSales1, txtDeduction1, txtAdjustment1 variables are camel cased in your javascript, but not on the html input name. So these return NaN.
UPDATE Also, you need to set the context of what you're referring to using the second parameter of a selector function:
$('.employee input[type="text"]').keyup(function(e) {
var $scope = $(this).closest('.employee');
var basic_salary = parseInt($('input[name^=txtMonthlyRate]', $scope).val());
var advance_salary = parseInt($('input[name^=txtAdvance]', $scope).val());
var recover_comm = parseInt($('input[name^=txtRecovery]', $scope).val());
var sales_comm = parseInt($('input[name^=txtSales]', $scope).val());
var deduction_salary = parseInt($('input[name^=txtDeduction]', $scope).val());
var adjustment_salary = parseInt($('input[name^=txtAdjustment]', $scope).val());
var total_sum = ((basic_salary+recover_comm+sales_comm) - (deduction_salary + advance_salary)) + adjustment_salary;
$('input[name^=txtTotal]', $scope).val(total_sum);
});
The txttotal1 needs to be changed to txtTotal1
The fiddle needs a closing }

How can I get data of selected table rows?

I am using the following snippet and from this I can find the index of a row which one is selected on the basis of checkbox on every row of the table.How can I modify this snippet so that I can get the selected row data instead of index?
Please Help!!
<script>
function myfunction3() {
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for (var i = 0; i < element_tableRows.length; i++) {
var checkerbox = element_tableRows[i].cells[0].firstChild;
if (checkerbox.checked) {
data = data+ element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
</script>
as TJ says, i dont see any index in your code. but try something like this which is cleaner
$('.collection tr').each(function () {
//processing this row
$(this).find('td input:checked').each(function () {
// there is checkbox and it is checked, do your business with it
var value_of_checkbox = $(this).val(); // which is 'data' that you wanted
});
});

Get textbox text in Javascript

I have a textbox which accepts date values like 01-01-2013. I need to get the year in javascript. This is the code I have used:
var oldRange, aOldRange;
var newRange, aNewRange;
aoldRange = new Array();
anewRange = new Array();
var oldYear, newYear;
oldRange = document.getElementById(
'<%= txtAcademicYearStartDate.ClientID%>').value;
aOldRange = oldRange.split("-");
oldYear = aoldRange[2];
But I get the value as undefined. What's the issue?
You have defined aOldRange, but refering to oldYear = aoldRange[2]
try
oldYear = aOldRange[2]
This example is tested and working fine please refer
<script language="javascript" >
var oldRange, aOldRange;
var newRange, aNewRange;
aoldRange = new Array();
anewRange = new Array();
var oldYear, newYear;
oldRange = '01-01-2013';
aOldRange = oldRange.split("-");
alert(aOldRange[2]);
</script>

Categories