i
HTML
<div id="notApprovedUsers">
</div><button onclick="approveUsers()">Approve</button>
</div>
i like to get checked users in parameter userList to work with.
here is javascript there me generating list with users and checkboxes.
i like to approve just the checked one's of course!
JavaScript
function getNotAssignedUsers() {
server.getUsersByGroup("1eb33e30-c355-467f-af3c-e7d0b4a1fgt5").then(function (userDetails) {
debugger;
for (var i = 0; i < userDetails.length; i++)
{
var vorname = userDetails[i].firstName;
var nachname = userDetails[i].lastName;
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = "0"+i;
document.getElementById("notApprovedUsers").appendChild(newCheckBox);
var newElement = document.createElement('div');
newElement.id = i;
newElement.className = "notApprovedUsers";
newElement.innerHTML = vorname + " " + nachname;
document.getElementById("notApprovedUsers").appendChild(newElement);
}
});
}
HERE in userList I need to read just a checked users..
function approveUsers(userList)
{
var user1 = document.getElementById("00").checked;
var user2 = document.getElementById("01").checked;
var user3 = document.getElementById("02").checked;
alert(user1 || user2 || user3);
}
You want something like this then. There may be errors as I havent tested
var names = [];
$('input[type=checkbox]:checked').each(function(index, value){
var name = $(value).next("div").html();
names.push(name);
});
Then do something with the names array
Edit - See jsfiddle http://jsfiddle.net/vpg3r/3/
I think the best solution for you here is to use jQuery. You can use something like:
$('#notApprovedUsers input[type=checkbox]:checked')
to get all the elements that are checked, and work with them.
I've created a JSFiddle for you to demonstrate how to implement the behavior that I'm describing. You can see it in this link.
Related
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
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 }
I've been trying to convert this section of script to jQuery instead of vanilla javascript, but I'm not sure how to loop through the elements with jQuery. Basically, I'm grabbing a data attr value from each field to be used as an error message that displays near the field.
This is all inside a click event on the submit button, FYI
What's the jQuery way?
//Set some variables
var invalidFields = $(form).querySelectorAll(':invalid'),
errorMessages = $(form).querySelectorAll('.error-message'),
parent;
// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[i]);
}
//Get custom messages from HTML data attribute for each invalid field
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
//Display custom messages
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.insertAdjacentHTML('beforeend', '<div class='error-message'>' +
invalidFields[i].validationMessage +
"</div>");
}
I converted your code one-to-one to jQuery. But there might be other ways, when i will know where form, setCustomValidity and validationMessage is coming from.
var $form = $(form);
// Remove any existing messages
$(".error-message", $form).remove();
// Get custom messages from HTML data attribute for each invalid field
$(".sdForm-input", $form).each(function() {
var message = $(this).attr('data-ErrorMessage');
// i don't know where the 'setCustomValidity' function is coming from
// this is a custom function
$(this)[0].setCustomValidity(message);
});
// Display custom messages
$(":invalid", $form).each(function() {
// i don't know where 'validationMessage' is comig from
// this is a custom property
$(this).parent().append("<div class='error-message'>" + $(this)[0].validationMessage + "</div>");
});
You can simple replace this.
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
Replace with jQuery way
var fields = form.find('.sdForm-input');
$.each(fields, function(index, el){
var message = $(el).attr('data-ErrorMessage');
$(el).setCustomValidity(message);
});
In my adventure to create a To-Do list application, I've run into another problem. In my code, every time a user clicks New Category a new div will appear with their custom name and number of forms.
However, when another div is created, its' forms are given to the previous div. Here's that code:
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type='text/javascript' src="script.js"></script>
<script>
$(function() {
$("#new").click(function() {
var canContinue = true;
var newCategory = prompt("Enter the name you want for your category:");
if(newCategory.length === 0){
confirm("A new category can not be created - nothing was entered in the text area.");
canContinue = false;
}
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
$("body").append("<div id = \"newDiv\"><p>" + newCategory + "</p></div>");
}
for(var i = 0; i < categorySections; i++){
$("#newDiv").append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
</script>
So, I tried creating a separate function using the this keyword where the forms were created after the div was ready, but now no forms are created at all!
Here's that code:
$(function(){
$("#newDiv").ready(function() {
for(var i = 0; i < categorySections; i++){
$(this).append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
So, how do I create forms for each separate div?
You're repeatedly creating divs with the same ID. (a) that's not legal and (b) if you do it anyway, your $(#newDiv) selector will always apply to the first one.
Also, you're appending to #newDiv outside the if (canContinue) check.
Try:
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
var newDiv = $("<div>").appendTo($(document.body));
var header = $('<p>').text(newCategory).appendTo(newDiv);
for(var i = 0; i < categorySections; i++){
newDiv.append("<form> Thing to do: <input type = \"text\"></form><br>");
}
}
jsFiddle
You can't use the ID newDiv multiple times, HTML IDs must be unique. Additionally, your flow can be cleaned up a bit, as below.
$(function () {
$("#new").click(function () {
var newCategory = prompt("Enter the name you want for your category:");
if (newCategory.length === 0) {
confirm("A new category can not be created - nothing was entered in the text area.");
return false;
}
var categorySections = prompt("Enter the number of sections needed for this category:");
var $div = $("<div />", {
html: "<p>" + newCategory + "</p>"
});
$("body").append($div);
for (var i = 0; i < categorySections; i++) {
$div.append("<form> Thing to do: <input type='text'/></form><br>");
}
});
});
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"
}
}
}