I have three text inputs :
First name
Last Name
User Name
In the form I have only these inputs are of type: text.
I want each one of them to be at least 4 characters long so I decided to validate them together.
I want to use Jquery to display an error message that is red when the length is less than 4 and green when it is greater.
I put three error messages respectively with the following Ids:
flength
llength
ulength
(the first letter corresponds to the input , example first name : flength and so on)
so here is my code to do this:
$('input [type= text]').keyup(function ({
var l = $(this).val();
var x = l.id;
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
Why wouldn't this script work? what should I modify?
Edit
demo
After seeing your comments
changing var x = $(this).attr("id"); wont fix the problem too
since $(this).attr("id") gives your current element id and your current element is your input tag element and you did not set the id attribute, Instead you have set it to div tags as you have mentioned in your comments, since you are trying to retrieve id attribute which you have not set and your getting an error.
One solution I could give is this way
<input type="text" name="flength"/> // set name attribute same as div ids
<input type="text" name="llength"/>
<input type="text" name="ulength"/>
$('input[type=text]').keyup(function ({
var l = $(this).val(); // get the input string
var x = $(this).attr('name'); // get the current input element name attribute
if (l.length < 4) {
$('#' + x).removeClass('valid').addClass('invalid');
} else {
$('#' + x).removeClass('invalid').addClass('valid');
}
});
Check this http://jsfiddle.net/Q2y8m/4/
Try this
$(document).ready(function () {
$('input[type=text]').keyup(function () {
var l = $(this).val();
var x = $(this).attr('id'); // notice it is not l.id
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
});
Demo http://jsfiddle.net/3yqVg/2/
Try to change var x = l.id; width var x = $(this).id;
Related
I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"
I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful
I have a scenario like
for(int i = 0; i < 10; i++)
{
<input type = "text" id="test"+i value="" onchange="getValue(i)">
}
I want to print selected text box value using jquery. I tried below code,....
function getValue(id)
{
var value = $("#test"+id).val();
alert(value);
}
Some how the above code is not working.
if i tried like var value = document.getElementById("test"+id); then it is working.
jsBin demo
var inp = ''; // String will hold all inputs
for(var i=0; i<10; i++){
inp += '<input type="text" id="test'+i+'" value="" />'; // Generate 10 inputs
}
$('body').append( inp ); // All inputs to HTML
$('input[id^="test"]').on('input', function(){
console.log( this.value );
});
You can't just drop raw HTML inside of a JavaScript loop like that. You have to set a string or create an element and append it to the DOM.
"getValue(i)" is a string. The "i" is not the variable i, it is literally a string with the letter i. If you want to concatenate strings and variables you have to do so like this:
var name = "Neil";
var greeting = "Hi, my name is " + name + ", nice to meet you!";
I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.
I have a jquery function and a javascript validation script running on the forms of my page.
On one form, the input IDs are generated dynamically with "." - this seems to be causing an issue and breaking the function.
Any obvious work around?
function:
function customAlert(){
var args = arguments;
if(args.length > 1) {
// check that custom alert was called with at least two arguments
var msg = args[0];
$(".giftmessaging").removeClass("alertRed");
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");
var div = $(".errorPopup");
div.css({"display":"block"});
div.html(msg);
for(var i = 1; i < args.length; i++) {
var inputID = args[i];
$("#"+inputID).addClass("CO_form_alert");
$(".giftmessaging").addClass("alertRed");
$('#' + inputID).focus();
$('#' + inputID).keydown(function() { $('.errorPopup').hide(); }).change(function() { $('.errorPopup').hide(); });
}
}
}
Example validation section:
couponAlert(msg_601,"frmCPN.Number_1")
and an example of the generated ids:
input title="Coupon <%=i%> Coupon Number" type="text" class="CO_PM_VisaCouponsNumberInput<%=redText%>" id ="<%=LLBECOrderConstants.LLB_PAYDEVICE_COUPONFORM%>.<%=LLBECOrderConstants.LLB_PAYDEVICE_NUMBER%>_<%=i%>" name="<%=LLBECOrderConstants.LLB_PAYDEVICE_NUMBER%>_<%=i%>" size="15" maxlength="15" value="<%=txtbxCPID%>" class="redeemNum" onKeyPress="return checkEnter(event,'<%=LLBECOrderConstants.LLB_PAYDEVICE_COUPONFORM%>')"/>
</div>
If you need to get an element by ID, and the ID has chars which jQuery could confuse for selector syntax ( ., :, etc), use the attr selector for ID instead:
$( '[id="' + inputID '"]' )