Using jquery, I'm trying to select those inputs that have an asterisk adjacent to them.
HTML
<form name="checkout">
<table width="100%" border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="FirstName" value="" />*</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="LastName" value="" /></td>
</tr>
</table>
</form>
Jquery
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
Result of elems should be 1 but it's not working, i.e. the form submits in spite of a return false in the handler so can't seem to catch the error details. What am I doing wrong?
var elems = $("td:contains('*') input");
This is selector for the input elements that you need.
elems.length will give you 1 in this case
Ha Ha,
Missing the onReady().
Use this one,
$(function(){
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
console.log(elems);
});
That should do. Cheers :).
I suggest you to use CSS :after pseudo element
<style>
.mandatory:after{
content:"*";
}
</style>
<span class="mandatroy">
<input type="text" name="FirstName" value="">
</span>
<script>
$("form[name='checkout'] .mandatory > :input")
</script>
It would be easier, if you added a class to the inputs which have an asterisk after them:
<td><input type="text" name="FirstName" class="required" />*</td>
Then you could select them by their class and do whatever you wish to them.
$("input.required").length();
Given the explicit requirement:
$('input').filter(function () {
return (this.nextSibling && this.nextSibling.nodeValue.indexOf('*') > -1) || (this.previousSibling && this.previousSibling.nodeValue.indexOf('*') > -1);
}).css('border-color','#f00');
JS Fiddle demo.
Related
Hi I am dynamically adding rows with a button and when I am finished entering information, I would like it to then clear the contents. The button "Add Pokemon" is the one I want to press and it should clear all the contents.
function addPokemon() {
var pokemonName = document.getElementById("pokemon-name-container");
pokemonName.innerHTML = document.getElementById("pokemon-names").value;
for (var i = 0; i < element.length; i++) {
if (element[i].value !== "undefined") {
pokemonArray.push(element[i].value);
}
}
console.log(pokemonArray);
for (var i = 0; i < pokemonArray.length; i++) {
document.getElementById("pokemon-container").innerHTML += "<li>" + pokemonArray[i] + "</li>";
}
document.getElementById("pokemon-name-container").value = "";
document.getElementById("move-name").value = "";
}
This is my function I am using. ^^
And below is my HTML vv
<div>
<table>
<tbody id="tbody">
<tr>
<td>
<div id="pokemon-name-container">
<p>Pokémon Name:</p>
<input type="text" id="pokemon-names" size="30">
</td>
</tr>
<tr>
<td>
<p class="moves">Moves:</p>
</td>
</tr>
<tr>
<td>
<input class="move-container" type="text" id="move-name" placeholder="Enter move here">
</td>
<td>
<input class="button-container" type="button" id="remove-btn" value="Remove Move" onclick="removeRow()">
</td>
</tr>
</tbody>
</table>
</div>
<div>
<input type="button" class="add-move-button" id="add-move-button" value="Add Move" onclick="addRow()">
</div>
<div>
<input type="button" class="add-pokemon-button" id="add-pokemon-button" value="Add Pokémon" onclick="addPokemon()">
</div>
You could put to all the inputs you create a unique class that defines them under a parent with a unique id. Then use inside the function of javascript the next pice of code const childs = document.querySelectorAll('#idParent.classChilds') this querySelectorAll is kind of like the getElementsById but uses selectors of CSS so it's more powerfull. The querySelectorAll returns you a NodeList of all the elements that matches de DOM with the CSS query.
Then you would only need to do something similar to this using functional programming:
const childs = document.querySelectorAll('#idParent .classChilds')
childs.forEach(child=>{
child.value = ""
})
I'm not sure if this code works (I'm not with an code editor and a browser to check if there isn't mistakes), as I said, you could do something similar to it
HOPE IS HELPFULL
FYI, try to avoid the selectors like getElementById or getElementsByClass....
Try to use this:
document.querySelector('CSS SELECTOR') // GIVES YOU THE FIRST MATCH OF THE CSS SELECTOR
document.querySelectorAll('CSS SELECTOR') // GIVES YOU A NODELIST WITH ALL MATCHES
I've already have validated my form using php but I would like to change it to use javascript.For some reason it doesn't seem to work, and I cannot understand why.
<form name="adminFormNewMember" method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>>
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter()" required autofocus></td>
</tr>
</table>
</form>
---------------------
<script>
function allLetter()
{
var text = document.getElementById("firstname");
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
return true;
}
else
{
alert("message");
return false;
}
}
</script>
Obviously the form contains more stuff, I've omitted them for the sake of clarity.
Also I'd like to use the same function for more field such as lastname etc, but I don't know how to do that since I'm using the getElementById
Finally, I'd like to just highlight the textfield red for errors, green for correct etc.
Clarification Edit I still need the PHP part I just don't want it to validate. I need the validation to happen for each field onBlur, and then the data to be passed to the php function to be inserted in a DB etc.
Try this :
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<form name="adminFormNewMember" method="post" >
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter(this.id)" required autofocus></td>
</tr>
</table>
</form>
<script>
var allLetter = function(id){
var text = document.getElementById(id).value;
if(text.length ==0 || text.toUpperCase().replace(/[^A-Z]/g, "").length != text.length) alert("Incorrect value")
}
</script>
</body>
</html>
To use your function with several fields, just pass the id as a parameter (this.id), in allLetters function, pass the parameter to getElementById.
It seems your Regexp is not correct (or suffiscient), so first check the field is not empty then check if length of value equals lenngth of value with letters only. If so the field is correct, otherwise go for the alert.
Maybe you should consider using jquery and the validate plugin here witch can save you lot of time
Returning true or false in your sample code is achieving nothing. What you need to do is, depending on whether validation is successful or not, add a CSS class to your input field. This CSS class should handle either background or border for your field to indicate that it did not match the criteria.
Instead of using onblur attribute, create an event listener for the blur event on your form fields. Delegate this listener to transfer control to a function which will take the value inside the event target and validate it. This should make your code more modular and apply to most fields.
Here is some code in basic javascript:
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" class="formFields"></td>
<td>Last Name </td>
<td><input type="text" id="lastname" class="formFields"></td>
<td>Fathers Name</td>
<td><input type="text" id="fathername" class="formFields"></td>
</tr>
<script>
for(var i=0; i < document.getElementsByClassName("formFields").length ; i++){
document.getElementsByClassName("formFields")[i].addEventListener("blur", function(evt){
var text = evt.target;
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
evt.target.classList.remove('incorrectField');
evt.target.classList.add('correctField');
}
else
{
evt.target.classList.add('incorrectField');
evt.target.classList.remove('correctField');
}
});
}
<style>
.incorrectField{
background: red;
}
.correctField{
background: green;
}
</style>
I have a table with some records, In each row tr I have two Textbox in two TD,
All textboxes don't have Id and Class, They just have a Name, Their Names Are like below
PurchaseDetails[some number].Quantity
PurchaseDetails[some number].PurchasePrice
Like:
PurchaseDetails[1457160526936].Quantity
PurchaseDetails[1457160526936].PurchasePrice
I use below codes but doesn't work:
var ProductQuantity = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].Quantity]").val();
var ProductPurchase = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].PurchasePrice]").val();
my complete html code is :
<tr >
<td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].Quantity" ></td>
<td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].PurchasePrice" ></td>
</tr>
If there is only one element with that prefix and suffix in the current context($(this)), attribute starts with selector and attribute ends with selector can be used.
$(this)
.find('input[name^="PurchaseDetails"][name$="Quantity"]').val();
You can use filter() for filtering using regex
// replace `$('input')` to `$(this).find('input')` to avoid searching in global context
var ProductQuantity = $("input").filter(function() {
return /^PurchaseDetails\[\d+\]\.Quantity$/.test(this.name);
}).val();
var ProductPurchasePrice = $("input").filter(function() {
return /^PurchaseDetails\[\d+\]\.PurchasePrice$/.test(this.name);
}).val();
console.log(ProductQuantity, ProductPurchasePrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="PurchaseDetails[1457160526936].Quantity" value=1 />
<input name="PurchaseDetails[1457160526936].PurchasePrice" value=2 />
<td id="RB_0_val_1">
<label for="RB_0_value_field_1" style="display:none;">Field Value</label>
<input type="text" id="RB_0_value_field_1"></td>
<td id="RB_0_extra_1"><input type="button" value="Select.." id="File"></td>
Now i need to find the id of textbox on th click of button.So i am using
var textboxid=$('input[id="File"]').closest('input[type="text"]').attr("id");
but value returned is undefined.
The id of the textbox is auto generated so i need to find the id on the click of the button.
How to do this?
Please replace your code with my code where just add prev() function.
var textboxid=$('input[id="File"]').prev().closest('input[type="text"]').attr("id");
Try utilizing .parentsUntil , :has()
$("#File").click(function() {
var textboxid = $(this).parentsUntil("td:has(:text)").find(":text").attr("id")
console.log(textboxid)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td id="RB_0_val_1">
<label for="RB_0_value_field_1" style="display:none;">Field Value</label>
<input type="text" id="RB_0_value_field_1">
</td>
<td id="RB_0_extra_1">
<input type="button" value="Select.." id="File">
</td>
</tr>
</tbody>
</table>
You can use jquery .prev() api, for doing that. Try the FIDDLE
Javascript code
$(document).ready(function(){
$('#File').click(function(e){
console.log($(this).prev('input[type=text]').prop('id'));
alert($(this).prev('input[type=text]').prop('id'));
e.preventDefault();
});
});
EDIT : For Updated markup provided in FIDDLE, I have used .closest() .prev() and .find() jquery api
$(document).ready(function () {
$('#File').click(function (e) {
var id = $(this).closest('td').prev('td').find('input[type=text]').prop('id');
alert(id);
e.preventDefault();
});
});
Hope this helps .....
I assume that the tds are inside a tr.
You can make this selector
var textboxid=$('input#File').parents('tr').find('label + input').attr("id");
Try this maybe (haven't tried it) :
var textboxid = $('#File').parent().find('input[type=text]').first().attr("id");
Should it be triggered by a click or something ?
Problem is the text box is in different td, try this:
$(function() {
$('#File').on('click', function() {
alert($(this).parent().prev('td').children('input[type=text]').prop('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<td id="RB_0_val_1">
<label for="RB_0_value_field_1" style="display:none;">Field Value</label>
<input type="text" id="RB_0_value_field_1">
</td>
<td id="RB_0_extra_1">
<input type="button" value="Select.." id="File">
</td>
</tr>
</table>
FIDDLE
$$(document).on('click', '#File', function() {
var qwe = $(this).parent().parent().find('input[type="text"]');
alert(qwe.attr('id'));
});
I have this code in my page. with two textboxes and one textarea.
<fieldset>
<legend><b>Search Criteria</b></legend>
<table>
<tr>
<td>
Find Text:
<input type="text" style="width:150px" id="txtFind"/>
<input type="button" id="btnfind" value=" Find "/>
</td>
</tr>
<tr>
<td>
Replace Text:
<input type="text" style="width:150px" id="Text1"/>
<input type="button" value="Replace Text" id="btnReplace"/>
</td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<legend><b>Result</b></legend>
<table>
<tr>
<td>
<%:Html.TextArea("Hello ASP.NET here")%>
</td>
</tr>
</table>
</fieldset>
in my first textbox if I enter "here" then I click the Find button it should find the text
if I enter "MVC" on second text box click Replace Text button it should replace the text "here" to "MVC" ("Hello ASP.NET MVC").,
Please can any one help me out? How to do this with javascript or jquery?
Thanks
Asuming your textarea has id="textarea", you should do this:
$("#btnfind").click(function(){
var find = $("#txtFind").val();
var replace = $("Text1").val();
var text = $("#textarea").val();
while(text.indexOf(find) >= 0){
text = text.replace(find, replace);
}
$("#textarea").val(text);
});
(Note that we're not using Regular expressions to replace because the text to find is dynamic so we'd have to escape the 'find' text).
Hope this helps. Cheers
this should get you started: http://jsfiddle.net/DD7t5/
using jQuery and a highlight jQuery plugin
var $result = $('#result'),
$txtFind = $('#txtFind'),
$txtReplace = $('#txtReplace');
$('#btnFind').click(function() {
$result.removeHighlight();
var findValue = $txtFind.val();
if (findValue.length > 0) {
$result.highlight(findValue) // find and highlight
}
});
$('#btnReplace').click(function() {
$result.text($result.text().replace(eval('/' + $txtFind.val() + '/gi'),
$txtReplace.val())); // replace
});