Javascript validation on input ID with - javascript

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 '"]' )

Related

Pull first instance of input and add id via JS

I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Getting ALL children from all levels

im about to develop a Formvalidator. I use a global Function which i call before every form-submit, i also give the form ID for accessing the inputs. so the function looks like this:
function FormValidation(formId)
{
var validated = true;
$("#" + formId ).each(function ()
{
var message="";
if ($(this).attr("data-validation-required") == "true" && $(this).val() == "") {
message += "-This field is required<br/>";
validated = false;
if (message != "")
$(this).after('<div class="popover fade bottom validation-error in" style="position:relative;display: block; margin-top:0px;"><div class="arrow" style="left:10% !important;"></div><div class="popover-content" style="color:#c0392b;">' + message + '</div></div>');
}
return validated; //true or false
}
so the problem is, that this each loop i wrote, is not accessing ALL children which are within the given "form" (by formId). Its accessing only the FIRST level children.
Here's some HTML example code:
<form id="myform">
<input type="text" data-validation-required="true"/> <-- will be accessed -->
<div class="SomeDivClass">
<input type="text" data-validation-required="true"/> <-- will NOT be accessed because 2nd level -->
</div>
</form>
<script>
$("#myform").submit(function(){
if(!FormValidation("myform"))
return false;
});
</script>
There are few issues in the given code
function FormValidation(formId) {
var validated = true;
//use descendant selector to find all required fields
$("#" + formId + ' [data-validation-required="true"]').each(function () {
//check whether the value is empty, if so mark as invalid
if ($(this).val() == "") {
var message = "-This field is required<br/>";
validated = false;
$(this).after('<div class="popover fade bottom validation-error in" style="position:relative;display: block; margin-top:0px;"><div class="arrow" style="left:10% !important;"></div><div class="popover-content" style="color:#c0392b;">' + message + '</div></div>');
} else {
//remove the validation of it is again become valid
$(this).next('.validation-error').remove()
}
//don't return the validated from the each loop since returning false here will cause the each loop to stop further iterations
})
return validated; //true or false
}
$("#myform").submit(function () {
if (!FormValidation("myform")) {
return false;
}
});
Demo: Fiddle
You could get all elements with data-validation-required via $('#' + formId +' [data-validation-required!=""]')
The jQuery API for traversing the DOM is incredibly well documented. To get all descendants of an element, you'd use .find(), along with a selector that didn't exclude anything — * — so your code would end up as follows:
$("#" + formId ).find( '*' ).each(function (){
But seeing as you're already creating a CSS selector to select the form, you may as well simply extend that selector:
$("#" + formId + " *").each(function (){
Your current form isn't even iterating the children — it's iterating over each form, and there's only one.

validating multiple inputs at the same time

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;

Print dynamic Text box value using JQuery

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!";

Populating anchor link from several textfields

I try to populate several textfields to become something like this Check
Below is my script that I modified from here but this script is only show inside textarea and how to show inside anchor link and generate something like Check.
<div id="textBoxContainer">
<input type="text" id="name" onkeyup="UpdateTextArea();" name="name" />
<input type="text" id="group" onkeyup="UpdateTextArea();" name="group" />
</div>
<textarea id="textAreaResult"></textarea>
Check
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + "&";
}
textAreaFinalResult.value = finalResult;
}
</script>
If you want to target an anchor tag instead of the textarea, then obviously you need to change that accordingly:
<a id="hrefResult" href="check.php">link</a>
Then in your updateTextArea function, you need to target the anchor's href rather than the textarea's value. There's several other optimizations that can be made in there also, such as making an array of name/value pairs and then doing a join on them so you don't end up with the trailing &, etc.
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var length = textboxes.length;
var target = document.getElementById("hrefResult");
var params = [];
var baseref = 'check.php';
for (var i = 0; i < length; i++) {
params.push(textboxes[i].id + "=" + textboxes[i].value);
}
target.href = baseref + '?' + params.join('&');
}
What the heck, here's a fiddle of the whole thing.
It would probably make sense to change the name of the function itself since there's no textarea involved anymore, but I leave that as something for you to do.

Categories

Resources