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)
})
Related
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 }
In my traveling website I want to filter the search result using multiple check boxes. Currently my code is working as follows.
If I check "Near Airport", it will show only the hotels with the data tag "airport". But when I want to filter the hotels which are near to both the air port and the shopping district at the same time, it will not work. It shows the list of hotels which have the data tag "airport" OR "shopping". I want to change it to list the hotels which have both data tags "airport" AND "shopping".
Screenshot of the web site http://prntscr.com/c49csj
Code in Context
$(document).ready(function(){
$('.category').on('change', function(){
var category_list = [];
$('#filters :input:checked').each(function(){
var category = $(this).val();
category_list.push(category);
});
if(category_list.length == 0)
$('.resultblock').fadeIn();
else {
$('.resultblock').each(function(){
var item = $(this).attr('data-tag');
var itemarr = item.split(',');
$this = $(this);
$.each(itemarr,function(ind,val){
if(jQuery.inArray(val,category_list) > -1){
$this.fadeIn('slow');
return false;
}
else
$this.hide();
});
});
}
});
});
You need to ensure that all elements in category_list array are available in itemarr array. The post How to check whether multiple values exist within an Javascript array should solve your problem e.g in the else block, modify your code as follows:
var item = $(this).attr('data-tag');
var itemarr = item.split(',');
var hideItem = false;
for(var i = 0 , len = itemarr.length; i < len && !hideItem; i++){
hideItem = ($.inArray(itemarr[i], category_list) == -1);
}
if(hideItem) {
$this.hide();
} else {
$this.fadeIn('slow');
}
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?
I'm writing a custom javascript validation script whereby i iterate through all input elements in a div named 'toggle' and select each that has a class named 'required' and if the value of the element is an empty string (empty) then i need to create labels containing the error message and place them right next to the textbox.
Here's the code:
function clientErrMsgs() {
var container = document.getElementById("toggle");
var inputArray = container.getElementsByTagName("input");
for (var i = 0; i < inputArray.length; i++) {
alert("");
if (inputArray[i].getAttribute("class") == "required" && inputArray[i].value == "") {
var errmsg = inputArray[i].getAttribute("data-errormessage");
var labelErr = document.CreateElement('label');
labelErr.id = "ErrMsg" + i;
labelErr.value = errmsg;
var parent = inputArray[i].parentNode;
parent.appendChild(labelErr);
}
}
}
the program executes well (tested it with alert()) up until the following line:
var labelErr = document.CreateElement('label');
Where is the problem?
you can use asp.net custom validator to do this
i am giving you an example, how to do this....
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Sms length is exceeding over 160."
ClientValidationFunction="validateLength" ControlToValidate="txtSmsMessage"
SetFocusOnError="True" ValidationGroup="add">*</asp:CustomValidator>
<script language="javascript" type="text/javascript">
function validateLength(oSrc, args)
{
args.IsValid = (args.Value.length < 160);
}
</script>
i suggest please try this...
I got things working with:
http://jsfiddle.net/ahallicks/kxPeN/2/
labels don't have a value attribute
Its document.createElement not document.CreateElement
MDC link : document.createElement
Update: you should access the innerHTML of the label and not the value
The snippet
var labelErr = document.createElement('label');
labelErr.id = "ErrMsg" + i;
labelErr.innerHTML= errmsg;
var parent = inputArray[i].parentNode;
parent.appendChild(labelErr);
This is not a direct answer to your question, but would your superior go for a different pre-built validation method? I'm partial to FlowPlayers jQuery based validator. Very simple to setup:
$("#myform").validator();
I've written several validation frameworks in the past. I finally got tired of reinventing the wheel.
May I suggest this:
function clientErrMsgs() {
var container = document.getElementById("toggle");
var inputArray = container.getElementsByTagName("input");
for (var inp, i=0, n=inputArray.length; i<n; i++) {
inp = inputArray[i];
if (inp.getAttribute("class") === "required") {
var errMsg = container.getElementById("ErrMsg"+i);
if (!errMsg) {
errMsg = document.createElement('span');
errMsg.id = "ErrMsg" + i;
errMsg.innerHTML= inp.getAttribute("data-errormessage");
inp.parentNode.appendChild(errMsg);
}
errMsg.style.display= (inp.value === "")?"":"none"
}
}
}
How do we stor selected row in array in JavaScript?
You shoud be more specific in what kind of object youre using in your html (DOM) code.
exampl:
if you're using a SELECT 'resources' in a form
var fl = form.resources.length -1;
//Pull selected resources and add them to list
for (fl; fl > -1; fl--) {
if (form.resources.options[fl].selected) {
theText = form.resources.options[fl].text;
theValue = form.resources.options[fl].value);
//your code to store in an aray goes here
//...
}
}
If I got it you want to store selected table rows using javaScript.
If yes, this may help.
This piece of code is to accumulate selected ID's (dataId), based on selection of selected row's id(elemId), in an input (hidId).
I have modified my original code to maintain the records in an Array as well.
function checkSelection(hidId,elemId,dataId)
{
var arr =
str = '_' + dataId + '_';
hid = document.getElementById(hidId);
row = document.getElementById(elemId);
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!hid.value.toString().includes(str)) {
hid.value = hid.value + str;
}
if(arr.includes(dataId))
arr.push(dataId);
}
else {
row.classList.remove("selected");
if(hid.value.toString().includes(str))
hid.value = hid.value.replace(str,"");
if(!arr.indexOf(dataId)==-1)
delete arr[arr.indexOf(dataId)];
}
alert(arr.toString());
}[I have tested it][1]
to focus more on the Array() a basic solution would be as below:
function checkSelect(hidId,elemId,dataId)
{
row = document.getElementById(elemId);
str = "";
if(document.getElementById(hidId).getAttribute("value")!=null)
str = str+document.getElementById(hidId).getAttribute("value");
str= str.replace('[','')
.replace(']','')
.replace('"','')
.replace('\\','');
document.getElementById(hidId).setAttribute("value",str);
alert(document.getElementById(hidId).value);
var arr = new Array();
if(document.getElementById(hidId).value.length!=0 ) {
arr=document.getElementById(hidId).value.split(',');
}
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!arr.includes(dataId.toString())) {
arr.push(dataId.toString());
}
}
else {
row.classList.remove("selected");
if(arr.includes(dataId.toString()))
{
delete dataId.toString();
arr.splice(arr.indexOf(dataId.toString()),1)
}
}
if(arr.length>0) {
document.getElementById(hidId).setAttribute("value", arr.toString());
}
else
document.getElementById(hidId).setAttribute("value", "");
}