Accessing element by class that called the method bind with onblur event - javascript

I have this html code :
<div id="jiraTicketAccordion">
<div>
<h3>key</h3>
<div>
<form>
<div id="jiraTable">
<table>
<tr>
<td class="label"><label for="arrival">ARRIVAL :</label></td>
<td><input type="text" name="arrival" class="arrival"
onblur="checkTime(this.value);"/></td>
<td class="label"><label for="newarrival">NEW ARRIVAL :</label></td>
<td><input type="text" name="newarrival" class="arrival"
onblur="checkTime(this.value);"/></td>
</tr>
</table>
</form>
</div>
</div>
</div><!-- end of accordion div -->
As you can see I have javascript function checkTime for onblur() event in that input box.
Earlier I had that text box with a unique id so I used document.getElementById for accessing it in my javascript function.
But now as there are many of accordion with same structure so I don't want to use unique ids for as there can be a large number.
So now I have a class for all those text boxes that require that validation.
But now I have to change my javascript functions where ever I used document.getElementById.
I know we can select elements by class in jquery, I also tried that but didn't get required results.
This is what I have tried in jquery:
function checkTime(dateTime){
alert("inside check time");
var errorMsg="";
regex = /^(\d{2})\/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\/\d{2} \d{2}:\d{2} [AP]M$/;
if(dateTime != ''){
if(!regex.test(dateTime)){
errorMsg = "Please enter date and time in the format: \n dd/MMM/YY HH:MM AM/PM";
alert(errorMsg);
//how to make the element that called this function to
//blank value it it failed validation
}
}
}
I wanted to access the element that called this method, so that I can manipulate that text box value.
And also I want to access other element by class in same accordion within that checkDate function.
I don't know how to make the text box vaalue to blank it it failed validation.
Earlier when I was having id ,I was doing it as :
document.getElementById('arrival').value='';

Shortest path from your current code is just passing the element instead of the value:
onblur="checkTime(this);"
Then on your function:
function checkTime(el){
var dateTime = el.value;
// rest of function
}
Personally, I'd avoid using inline event handlers like onblur="...", and use addEventListener to bind the handlers directly from JavaScript. That would be one step further towards decoupling logic, structure and presentation.

Related

How to give multiple class to single html element

I have created one IMS system. In that, on order page, I have to validate product quantity before generating the order. So for that, I have used jquery selector to compare two values unless the value of the second field will be less than or equal to the first field submit button will be enabled and whenever values go above it button will be disabled. (the first field is stock available and second field is stock given at the time of creating order). but this code is working for an only first product when I enter second product validation is not working. How can i put this code in the loop and I can check every product in an order. An id of a row is automatic incrementing while adding the new product. Below is my code
<td>
<input type="text" name="qty[]" id="qty_1" class="form-control" disabled autocomplete="off">
<input type="hidden" name="qty_value[]" id="qty_value_1" class="form-control" autocomplete="off">
</td>
<td><input type="text" name="aqty[]" id="aqty_1" class="form-control" required onkeyup="getTotal(1)"></td>
Javascript
<script type="text/javascript">
$('#qty_value_1,#aqty_1').on('keyup', function() {
var btn = $('button:contains("Submit")');
if (parseFloat($('#qty_value_1').val()) >= parseFloat($('#aqty_1').val())) {
btn.prop('disabled', false);
} else {
btn.prop('disabled', true);
}
})
</script>
My main intention is to check every product quantity before generating the order
you can use multiple classes in html one div or ...
<div class="container classname classname classname">
</div>
you need to use CSS attribute selector. it uses square brackets. For your case you need to select id-s that begin with aqty_, thus you have to define selector as [id^="aqty_"]
Your script may look as follow
<script type="text/javascript">
var btn = $('button:contains("Submit")');
$('[id^="aqty_"]').on('keyup', function() {
var qty_val = $(this).closest('tr').find('[id^="qty_value_"]');
if (parseFloat(qty_val.val()) >= parseFloat($(this).val())) {
$(this).removeClass("warn");
} else {
$(this).addClass("warn");
}
btn.prop('disabled', $('.warn').length);
});
</script>
Since you have several goods to fill order you have to concern about enabling of button only when all quantities of order don't exceed store values. So the good way is to define class i.e. .warn which signs wrong field value.
Last step of script has to be to check in a length of array of elements with class .warn. If this length is more than zero, then some value exceeds its limit, else all inputs are good and submit button becomes enabled.
Look at link how it works: jsfiddle link

Mark row for deleting using checkbox

I have this inbox or mails which I needed to mark using checkbox for multiple deletions. The problem is that when I click the checkbox it always go to method read() because of onclick inside the tag. All I want is simple marking. Please see the code below:
#foreach ($messages as $message)
<tr onclick="document.location='{{route('account.message.read', array($message->id))}}'">
<td> <input type="checkbox" name="msg" value="{{$message->id}}"></td>
<td><strong>{{Str::words($message->subject, 5, '...')}}</strong> {{Str::words($message->message, 20, '...')}}</td>
</tr>
#endforeach
Now how can I mark each row without going inside that method? I am a newbie btw.
All you need to is attach handler to checkbox and use stopPropagation from bubbling up into trees, see below example :
HTML
Supposed we have table rows with onclick inline javascript and inside it have input:
<table>
<tr onclick="return alert('Hai')">
<td>
<input type="checkbox" />Click Me
</td>
</tr>
<table>
And here the handler :
$('input').click(function(e){
// normally if we removed this line of code
// alert will getting called as checkbox is checked/unchecked
// was inside table rows
// but with this propagation, we disabled it
// from bubbling up into tree
e.stopPropagation();
});
DEMO
you could put the onclick inside the tags excluding the checkbox cell
otherwise you could call an actual onclick function while capturing the click event and check that x is greater than lets say 50px!
<script type="text/javascript">
document.getElementById('emailRow1').addEventListener("click",function(e){
var x=e.pageX-this.offsetLeft;
if(x>50){
rowClicked();
}
},true);
</script>
<table><tbody><tr id='emailRow1'><td style="width:50px;">This area wont trigger onclick</td><td>I trigger onclick</td><td>i trigger onclick</td>
Then you can set custom parameters on your object and recall them using this.customPropertyName to determine what row was clicked! hope this helps

Checking the names of elements from an array of objects selected by jquery

I'm a beginner in js and jquery library. I'd like to get an array of input fields with a particular name, and validate input. Each of my input fields have a name like NS[0], NS[1] etc. The total number of fields will have to be determined by the code, since the fields are generated by javascript.
I know that I can have jquery address the individual object like this:
$("input[name=NS\\[0\\]]").val() for <input type="text" name="NS[0]">.
However, how can I get an array of all these similiar elements, from NS[0] to NS[x] where x has to be determined based on how many fields have been generated? I already have other fields with different name patterns sharing the same css class, so using class is not an option. These boxes are in a particular div area, but in the same area are other input fields, so choosing all input boxes of the same area selects them as well.
In other words, how do I use jquery to check the name of each input field, after getting the entire array of input fields, to check each individual name?
Since I have input fields of various names in the area determined by the table id CNTR1, I would select them with $('#CNTR1 input'). I can also select individual fields by using $("input[name=]"). However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
The html code:
<table class="table" id="cnservers">
<thead>
<tr>
<th>Type</th>
<th>Preference</th>
<th>Value</th>
<th>Name</th>
</tr>
</thead>
<tr id="CNTR0">
<td>CNAME</td><td><input type="text" name="CN_PREF[0]" value=""></td><td>
<input type="text" name="CN_VAL[0]" value=""></td><td>
<input type="text" name="CN_NAME[0]" value="">
<a class="btn btn-danger" onclick="DelField(this.id);" id="CN_D0" >
<span class="btn-label">Delete
</span>
</a>
<a class="btn btn-primary" onclick="addField('cnservers','CN',10);" id="CN_A0" >
<span class="btn-label">Add
</span>
</td></tr>
</table>
[1]: http://i.stack.imgur.com/bm0Jq.jpg
I must be missing something. Is there a reason you can't use the http://api.jquery.com/attribute-starts-with-selector/?
$('#CNTR1').find('input[name^="NS"]')
Regarding,
However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
$("#CNTR1 input").each(function(index, elem) {
var $elem = $(elem),
name = $elem.attr('name');
var nameMatchesCondition = true; // replace with your condition
if (nameMatchesCondition) {
// do something!
}
});
EDIT 1:
Well, id is still an attribute of an html element. So you could do $('[id^="CNTR1"]') ... The value of the id attribute of an element doesn't contain the #. It's only part of the css/jquery selector. When using attribute style selectors, you don't need it. Though I can't comment on the performance of this.
Ideally, you want to attach a second class, say js-cntr to all elements that you created with an id starting with CNTR. Even though different name pattern elements may already have one class, that class is for styling. There is no stopping you from attaching custom classes purely for selection via js. This is an accepted thing to do and which is why the class name starts with js-, to denote that its purely for use via js for selection.
Try this
HTML
<table id="CNTR1">
<tr>
<td>CNAME</td>
<td><input type="text" name="CN_PREF[1]" id="CN_IN[1]"></td>
<td><input type="text" name="CN_VAL[1]"></td>
<td><input type="text" name="CN_NAME[1]"></td>
</tr>
</table>
JS
$(document).ready(function(){
$("#CNTR1 input").each(function() {
console.log($(this).attr("name"));
// Match With predetermined criteria
});
});
Use jQuery's .filter method, with a filter function:
filterCritera = /^CN_NAME\[/; // or whatever your criteria is
var inputs = $('#CNTR0 input');
// you could also cache this filter in a variable
inputs.filter(function(index){
return filterCritera.test(this.name);
}).css('background','red');
jsbin
The markup you posted does not the markup described in your question ( it does not contain NS[0]) but you can substitute it in the reguluar expression above.

show submit <a href> link onchange and pass the value of the input box changed

I am not a JavaScript person really, I write in ASP and use a SQL database in the backend. But our marketing director requested a change that will use JavaScript.
On our view cart page, we're currently displaying an input box with a modify button to allow customers to change the quantity of the listed item (in that row... there could be multiple products in their cart, each having their own quantity input).
<form method="post" action="updateitem.asp">
<input type="hidden" name="product_id" value="<%= PRODUCT_ID %>">
Quantity: <input type"text" name="quantity">
<input type="image" name="Submit" src="/graphics/modify.gif" align="middle" border="0" alt="Continue">
</form>
What I'd like to make work is something like this. Hrm, assuming I need to do my form/div name differently for each product? I can easily write the product_id into the id tags but then assuming I'd also need to loop through my function for each one. I've gotten this far in writing the replacement code:
Get Dataset from Database (items in cart) and loop through:
<form method="post" action="updateitem.asp" id="updateitems<%= PRODUCT_ID %>">
Quantity: <input type="text" name="qty<%= PRODUCT_ID %>" OnChange="Javascript:UpdateQty()")
<div id="showlink<%= PRODUCT_ID %>">
<br /><span class="BodyTiny">update</span>
</div>
</form>
END LOOP
So if the quantity changes, it displays the word "update" where they can click and it passes whatever quantity that is in the quantity field to the updateitem.asp (in a way I can then update it in the database in ASP/SQL). In the code above, if we could just insert the new # in the a href statement after quantity=, then I could fix it in the updateitems.asp page without a problem.
I'm not sure where to even begin honestly, I have this so far:
LOOP through dataset so each product has its own function
<script Language="JavaScript">
<!--
function UpdateQty(updateitems<%= PRODUCT_ID %>) {
Show div updateitems<%= PRODUCT_ID %>
Replace NEWQUANT within that div with the value in the input field qty<%= PRODUCT_ID %>
}
//-->
</script>
END LOOP
I'm having a few problems...
I am not sure how to write the function UpdateQty. It should A) display the stuff in div id=showlink, and B) add the # from the input named quantity quantity to the href so I can update it in the database on the next page
If they have JavaScript turned off, they should be able to enter a new quantity and just hit enter for it to submit the form. I believe this will work as its a form with 1 text input and 1 hidden one, so just hitting enter in the text input should submit it. But that should still work with whatever JavaScript is added to make the showlink div show if it changes.
Do I need to add a class to my CSS for showlink? If so, what do I need to put in it?
Any help would be greatly appreciated!
Mahalo!
so what you can do for updateQty is have one function that will be correct for all products in a list just by making a function that finds all the necessary elements by relative paths.
//in this function the context is the element, so the
//`this` variable can be used rather than a param
//for the product id
function updateQty() {
//show the update link
var parent = this.parentNode;
//assumes only the update text uses the class bodyTiny, and that there
//is only one element using it. obviously making this invariant true
//would be trivial by adding a different class name
var updateText = parent.getElementsByClassName("bodyTiny")[0];
updateText.style.display = 'block';
var updateLink = updateText.parentNode
, updateHref = updateLink.href;
//next we find the current quantity and replace it with the input
updateHref = updateHref.replace(/qty=(\d*)/, 'qty='+this.value);
//then we set the link element's attribute
updateLink.href = updateHref;
//now when you mouse over the link you should see the url has changed
}
You can also set your form to POST the equivalent data, and then I guess on the server side you will have your OnGetPage and OnPostback both delegate to the same method with the parameters either parsed out of the query string or out of the post data.
You can see it running on jsfiddle. Hopefully this helps!

Accessing a text box inside table row using javascript

I am using the following code
<tr id="row">
<td><input type="text" name ="first" id="first" onclick="goto("row")"/>
</td>
<td><input type="text" name ="second" id="second"/>
</td>
</tr>
<script>
function goto(row)
{
var row=document.getElementById("row");
}
</script>
here in the goto() function i am getting the table row by using id.I need to get the second text box inside this row when i clicking the first text box.How can i get the second text box using the table row id. Any idea ?.
First off, you're missing some equals (=) signs in your HTML. You might want to change that to name="first" and name="second". Secondly, I'm not sure why you have two elements with the same id of "second" when you could have changed one of them to "first" so they don't collide, and then you could easily select the second one with getElementById("second"). Simple mistake, right?
Change the ids, make them unique and you could directly access the input textbox like:
var txtbox = document.getElementById("YourTextboxId");

Categories

Resources