I'm working on a .net website and I have a bit of a situation.
Say I have...
<input type="text" class="name" id="name">
<p></p>
<input type="text" class="surname" id="surname">
<p>Error!</p>
What Id like to do, using javascript, is detect that the second paragraph tag says 'Error!' and add a class to the input tag before it.
I know this seems like a bit of a strange way of working but any advice would be greatly appreciated!
Hi all, the adivce and answers i was given worked fine on a fresh page on jsfiddle only i cant seem to get them to work on my actual site.
My P and input tags are constructed like this....
<li class="yourdetli">
<label class="yourdet">Street Name</label>
<input type="text" id="ctl00_ContentPlaceHolder1_TB_SName" name="ctl00$ContentPlaceHolder1$TB_SName">
<span style="color: Red; display: none;" class="errorp" id="ctl00_ContentPlaceHolder1_RequiredFieldValidator6">
<p>You must complete this field</p></span>
</li>
and my JS is...
<script type="text/javascript">
$(document).ready(function() {
$('p:contains("You must complete this field")').prev('input').addClass('error');
});
</script>
only for some reason it doesnt seem to add my class, can anybody see why?
You can use
$('p:contains("Error")').prev('input').addClass('error');
Maybe try
$("p:eq(1):contains('Error!')").prev('input').addClass('error');
You can check the text value of the second <p> tag by using jQuery. You'll need a selector that finds it (in this example, it is the last <p> tag).
if ($("p").last().text() == "Error!") {
$("input#surname").addClass("myClass");
// do other stuff here
}
Try -
if ($("input#surname").next("p:contains('Error!')").length > 0) {
$("input#surname").addClass('yourclass');
}
I'd recommend adding the error css class to your validator's CssClass property so that its already rendered server side. This way if you change your error message, you won't have to change any javascript to display it.
<asp:RequiredFieldValidator ID="requiredValidator" CssClass="error" ControlToValidate="..." ErrorMessage="You must complete this field"/>
Or if you're looking to style all of your validators with the same class, you can add the following script to your master page.
$(document).ready(function()
{
if (Page_Validators != null)
{
for (i = 0; i < Page_Validators.length; i++)
{
Page_Validators[i].className = "error";
}
}
});
See http://www.jrummell.com/blog/index.php/2009/08/apply-the-same-css-class-to-all-validators-in-a-web-project/ for more information.
Related
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); } else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
I've been attempting to do this with jQuery, but it hasn't been functioning properly, I have also done a thorough amount of research for ways to condense this code. I was trying to condense the statement with a ternary operator. If you could please assist me with a possible solution that would be great! Thanks (Ternary Solution would be amazing)
The issue with your code is that you have mis-matched quotes in the HTML due to the console.log("X") calls in your code that is messing up the attributes of the input element. If you check the console you'll most likely see some errors relating to this.
It's for this reason, amongst many others, that it's considered bad practice to use inline script (or CSS styling for that matter). The other issues are that it's bad for separation of concerns and makes the code harder to read an edit. It's far better practice to attach your event handlers using unobtrusive Javascript, like this:
$('.seasonal-checkbox').change(function() {
$('#ShowIfChecked').toggle(this.checked);
$('#HideIfChecked').toggle(!this.checked);
});
#ShowIfChecked {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" class="seasonal-checkbox" />
<div id="ShowIfChecked">Checked!</div>
<div id="HideIfChecked">Not Checked!</div>
Note the use of the change event over click, so that the event is still fired for user who navigate the web using the keyboard. Also note the simplified logic using toggle() to hide and show the relevant content in a single call to each method which negates the need for an if statement - and by proxy a ternary expression too.
You can change your onclick to a function, because at least for me, it is easier to see whats really going on.
So change
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal"
onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); }
else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
to
<input type="checkbox" runat="server"
name="Seasonal" value="Seasonal" id="isASeasonal" onclick="myFuncton(this)" />
Within your view:
<script>
myFunction(myCheckBox)
{
if(myCheckBox.Checked)
{
console.log('Worky');
$('#ShowIfChecked').show();
$('#HideIfChecked').hide();
}
else
{
$('#HideIfChecked').show(); console.log("No Worky");
}
}
</script>
Now to get the expression/Ternary Solution you want, you can change this script to look like this:
<script>
myFunction(myCheckBox)
{
myCheckBox.Checked ? (console.log('Worky'), $('#ShowIfChecked').show(),
$('#HideIfChecked').hide()); : ($('#HideIfChecked').show(), console.log("No Worky"));
}
</script>
You can find more Info about Ternary Solutions here
We dont write code like this. It fails on every code review.
Do this:
$('#isASeasonal').click(function() { ...});
https://api.jquery.com/click/
Seasonal Address:  <input type="checkbox" runat="server" clientidmode="Static" name="Seasonal" value="Seasonal" id="isASeasonal"/>
$('#ShowIfChecked').hide(); //Hid What needs to be shown if checked.
$("#isASeasonal").click(function () { //Used Click event on checkBox
($("#isASeasonal").is(':checked')) ? (console.log('worky'), $('#ShowIfChecked').show(), $('#HideIfChecked').hide()) : (console.log('no worky'), $('#HideIfChecked').show(), $('#ShowIfChecked').hide());
What fixed my issue was that in ASP.net I needed to add clientidmode="static" to the div's that I was trying to hide & show. I still don't understand the reason why, I'm currently looking more into it but this is what worked for me but above you can see the majority of the final product with the ternary operator!! Yay.
I can't for the life of me figure out why this isn't working.
I want to search the current page for text using a search box. I googled and found this: http://www.javascripter.net/faq/searchin.htm . I implemented the code into my site, but it doesn't work. the function ( findString() ) works, but only when I hard-code a string (as in i can't use javascript or jquery to get the value of a text input). I made this fiddle: http://jsfiddle.net/alyda/CPJrh/4/ to illustrate the problem.
You can uncomment different lines to see what I've tested.
jQuery has a method :contains() that will make easier what you are looking for.
Take a look here: fiddle
$("button[type='submit']").click(function () {
var string = $('#search').val();
var matched = $('li:contains(' + string + ')');
matched.css('color','red');
console.log(matched);
return false;
});
I found a fix (sort of). It seems that the input needs to be placed well AFTER the content to be searched in the DOM. That means I've done the following:
<section class="content">
<h2>Fire</h2>
<h3>Fire Extinguishers</h3>
<ul>
<li>Model 240</li>
<li>Model C352, C352TS</li>
<li>Model C354, C354TS</li>
</ul>
...
<div id="navbar">
<ul>
...
</ul>
<input id="search" type="text" class="form-control pull-left" placeholder="Search for part number">
<button id="submit" type="submit" class="btn btn-default pull-left" style=" margin-top:6px;">Search</button>
</div>
as you can see, I've moved the input (which is in the navbar div) BELOW all of the text I want to search, and used CSS to programmatically place the navbar at the top of the page. I don't particularly like this setup (as it messes with the flow of content) but since I was looking for the quickest and simplest implementation of a single-page search, it will have to do.
I would still love to know why this happens, when the javascript is at the end of the DOM where it belongs...
In firefox I noticed that the fiddle (v4) as given in the question worked, but not in the way the asker expected it to.
What happens in firefox is that the function does find the value..: you have just entered it in the input-field. Then the browser's find method seems to hang in the 'context' of the input 'control' and doesn't break out of it. Since the browser will continue to search from the last active position, if you select anything after the input-field, the function works as expected. So the trick is not to get 'trapped' in the input-field at the start of your search.
A basic (dirty) example on how to break out of it (not necessarily the proper solution nor pure jquery, but might inspire a useful routine, since you now know the root of the problem in FF):
$( "button[type='submit']" ).click(function(){
var tst=$('#search').val(); //close over value
$('#search').val(''); //clear input
if(tst){ //sanity check
this.nextSibling.onclick=function(){findString( tst );}; //example how to proceed
findString( tst ); //find first value
} else { alert('please enter something to search for'); }
return false;
});
Example fiddle is tested (working) in FF.
PS: given your specific example using <li>, I do feel Sergio's answer would be a more appropriate solution, especially since that would never run line: alert ("Opera browsers not supported, sorry..."), but the proper answer to your window.find question is still an interesting one!
PS2: if you essentially are using (or replicating) the browser's search-function, why not educate the user and instruct them to hit Ctrl+F?
Hope this helps!
I had same problem in an angularjs app and I fix it by changing DOM structure.
my HTML code was something like this:
<body>
<div class="content" >
<input class="searchInput" />
<p>
content ....
</p>
</div>
</body>
and I changed it to something like this:
<body>
<div class="search">
<input class="searchInput" />
</div>
<div class="content">
<p>
content ....
</p>
</div>
</body>
Note: I'm aware that this topic is old.
need some help! am trying to get the value of the below input id "j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" and have tried jquery and javascript such as: document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63") but keep getting a null result. ID can't be changed either, any help appreciated
<td class="sf42_cell_bottom_light"><span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61"><input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417"></span></td>
Use this:
$("[id='j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61']")
By the way, since you are apperently using JSF, this is a good practice to set id to each component to avoid such horrible ids (who can changes if you add/remove components).
See more information in this thread:
Handling colon in element ID with jQuery
Do you have any control of the element? Can you add a class to it?
var val= document.getElementsByClassName("TheClassName");
Or you can get the TD with class sf42_cell_bottom_light (if it is unique) then get its INPUT elements by:
var theTd= document.getElementsByClassName("sf42_cell_bottom_light");
var val = theTD.getElementsByTagName("INPUT");
I need to see more of the HTML to give you an better answer.
You may need to escape colon in your id .So
try this
function RemoveInvalidCharacter(myid) {
return '#' + myid.replace(/(:|\.|\[|\])/g, "\\$1");
}
And call like this
$(RemoveInvalidCharacter('j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61'));
Have a look at How do I select an element by an ID that has characters used in CSS notation
I have tested this code:
<td class="sf42_cell_bottom_light">
<span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61">
<input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417">
</span>
</td>
<script type="text/javascript">
document.write(document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63").value);
</script>
in FF, IE, Chrome (the latest versions)... and seems to work ok... ar you sure it is about this id?
Replace:
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63")
with
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63")
The id is different.
http://jsfiddle.net/wNePW/
I have this snippet of HTML:
<div class="clearfix" id="menu-file-div">
<label id="menu-file-label" for="id_menu_file">From File</label>
<div class="input">
<div id="file-upload">
<input type="hidden" name="menu_file" id="id_menu_file" />
<script type="text/javascript">var field_id = "id_menu_file";</script>
<script type="text/javascript">var append_to_element_id = "menu-upload";</script>
<script type="text/javascript">var loader_element_id = "newmenu-modal";</script>
<noscript>
<p>Please enable JavaScipt to upload a file.</p>
</noscript>
</div>
</div>
</div>
In my console, when I try to use the jquery id selector, it fails to return the input element:
> $("#id_menu_file")
[]
Any thoughts on why this is so? I feel like I'm missing something simple. Thank you!
EDIT - some other javascript was removing the element, that is why it's not showing up. Thanks all for your help.
To repeat my first answer (which may be applicable to others reading this post later, and which was deleted despite the fact that it "fundamentally answer[ed] the question"):
Is this HTML inside of a frame (iframe or regular)? That could make it difficult for jQuery to find your element, unless you give it the right context.
To add a context to a jQuery selector you just provide that context as an extra argument, for example: $('TD', aFrameElement);
If the element in question is not inside a frame (which is the case for zallarak), the problem is almost certainly a timing issue: the jQuery selection is happening before the element has gotten loaded on the page. You can test this theory by adding the following code (anywhere):
$(function(){
console.log($("#id_menu_file"))
});
If that is the problem, simply wrap your code in $(function(){ to fix matters.
try :
$("#id_menu_file").get(0)
$(selector) return arrays
Please check the link below:
http://jsfiddle.net/cT9kg/4/
As you can see its a search field with a button.
If you have trouble understanding what I mean below please just look at the "Title" input on the Ask a question page.
The input has autofocus on.
BUT
How can I have it so text is already in the input with autofocus on but as soon as someone types into the input the text disappears.
AND
When someone has entered text in the input but then deletes it, it goes back to the way it was at the beginning: on focus with text in it instructing the person what to type in the input.
Thanks!
James
You could define the default value.
On focus - empty value, if the value is default value.
When the element lose the focus, You could check, if it's empty, and if Yes - restore the default value.
I've tested this as working, just make sure you put the <script> part just before the </body> tag.
<input type="text" class="input1" autofocus="focus" id="search" value="Type here..." onKeyPress="checkValue()" />
----
<script type="text/javascript">
var searchEl = document.getElementById('search');
var defaultValue = searchEl.value;
function checkValue() {
if (searchEl.value == defaultValue) {
searchEl.value = "";
}
}
</script>
You could use the HTML placeholder attribute, but in the majority of browsers that won't achieve quite what you are after: as soon as the input is focused, the placeholder text disappears.
For functionality akin to iOS (found on sites such as Twitter as well), you need to use JavaScript. One example can be seen online here.
This similar question (and this one) have some useful alternatives and code examples.
You're correctly using autofocus, which is fine but has patchy browser support. You can add in a JS fallback, like this (taken from here):
<script>
window.onload = function () {
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("s").focus();
}
}
</script>
Wow. I tried digging around in the source code for the Ask a question page. Talk about convoluted.
Here is the CSS File.
While it seems the relevant bits are thus, they don't seem to DO much more than format (other than the edit-field-overlay trick.
.form-item {padding:10px 0px 15px 0px;}
.ask-title {margin-bottom:-15px;margin-top:-10px;}
.ask-title-table {width:668px;}
.ask-title-field {width:610px;}
.ask-title-cell-value {padding-left:5px;}
.edit-field-overlay {display:none;}
HTML (some TD tags removed):
<div class="form-item ask-title">
<table class="ask-title-table">
<tr>
<td class="ask-title-cell-value">
<input id="title" name="title" type="text" maxlength="300" tabindex="100" class="ask-title-field" value="">
<span class="edit-field-overlay">what's your programming question? be specific.</span>
</td>
</tr>
</table>
</div>
But I totally could NOT figure out the relevant Javascript bits. As there are NO onEvent handlers for this form that I can see, the only reference to this field (title) would be in the prepareEditor function.
Anybody care to try and explain it to a relative newbie??