Having problems with the following - Not working as expected, getting JS doc errors as well.
JSFiddle Nota Worka.
try this fiddle: http://jsfiddle.net/maniator/egjF4/6/
and change the if line to:
if (document.forms['myform'].selectbox1.selectedIndex == 2)
you need the == to check values
UPDATE
Based on your comments below here is the jQuery for the same thing:
$(function(){
$('#selectbox1').change(function(){
if(this.selectedIndex == 2){
$('#input1, #input2, #asterisk').css('visibility', 'visible');
$('#input2').addClass('required');
}
else {
$('input, #asterisk').css('visibility', 'hidden');
$('#input2').removeClass('required');
}
})
})
you could also do this, http://jsfiddle.net/edelman/egjF4/10/
var form = document.getElementById('myform');
if (form.selectbox1.selectedIndex == 2)
this way you're caching the form in case you want to reference it later, preventing another element lookup and speeding up your code.
I believe jsfiddle runs in it's own little protective XPC bubble, so showhidebtime will not be seen as defined via an inline javascript call. Best practice is to always add events in the javascript file, not inline with the elements.
Also you need to change your form to show name="myform" in order for document.myform to work.
Try this fiddle: http://jsfiddle.net/garreh/qb6fw/
Related
I have an problem with my site when I want to change the css style from the JavaScript it works but only for few seconds.
function validateForm() {
var fname = document.getElementById('<%=UserFnameTextBox.ClientID%>');
if (fname.value == "") {
document.getElementById("WarnUserFnameTextBox").style.opacity = 1;
document.getElementById('<%=UserFnameTextBox.ClientID%>').style.borderColor = "red";
getElementById('<%=UserFnameTextBox.ClientID%>').focus;
}
}
I'm using also Asp.net, that's why I wrote the ID like this
I want that the JS will save the style for as long that the user enter the textbox.
Multiple things here: I suggest that your validateForm() function triggers in an onClick on your submit-button, right? Does your button look somewhat like this?
<input type="submit" value="submit" onClick="validateForm()">
If this is the case, the reason why your styles work only for few seconds is simply that the website reloads. The styles are in effect, but the form is also triggering and send to the site, which you added in your <form action>. After reloading, the website will fall back to its default style, as if the errors never occured... which is correct on that instance of the site.
If you want to have it permanent, you have to disable the submit-button as long as there are invalid fields. You can make use of the required attribute for form elements as well, since the form won't submit as long as there are invalid fields. These can be styled as well.
Have a look at these CSS rules for that:
/* style all elements with a required attribute */
:required {
background: red;
}
You can make use of jQuery as well and disable the form-submit with preventDefault. You can take care of every style and adjust accordingly, as long as there empty / non-valid characters in your input-fields. I suggest combining this with the onKeyUp-function. This way you check everytime the users releases a key and can react as soon as your input is valid.
As an example with jQuery:
var $fname = $('#<%=UserFnameTextBox.ClientID%>');
var $textBox = $('#WarnUserFnameTextBox');
$fname.on("input", function() {
var $this = $(this);
if($this.val() == "") {
$textBox.show();
$this.focus().css("border", "1px solid red");
}
});
(thanks for pointing out my errors and optimizing the code, #mplungjan!).
To "disable" the actual form-submission, refer to this answer:
https://stackoverflow.com/a/6462306/3372043
$("#yourFormID").submit(function(e){
return false;
});
This is untested, feel free to point out my mistake, since I can't check it right now. You can play around on how you want to approach your "errorhandling", maybe switch to onKeyDown() or change(), that kind of depends on your needs / usecase.
Since your question isn't tagged with jQuery, have a look at this answer given by mplungjan as well, since it uses native JS without any framework.
https://stackoverflow.com/a/53777747/3372043
This is likely what you want. It will stop the form from being submitted and is reusing the field and resetting if no error
It assumes <form id="myForm"
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var field = document.getElementById('<%=UserFnameTextBox.ClientID%>');
var error = field.value.trim() === "";
document.getElementById("WarnUserFnameTextBox").style.opacity = error ? "1" : "0"; // or style.display=error?"block":"none";
field.style.borderColor = error ? "red" : "black"; // reset if no error
if (error) {
field.focus();
e.preventDefault();
}
});
});
Weird problem. I'm modifying shop template:
https://demo.themeisle.com/shop-isle/product-category/clothing/dresses/
At this moment when you hover product's picture there will show "add to cart" button. This is .
Under picture there is price
I prepared code:
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
Nothing happens. This code work only if I set timeout:
setTimeout(function() {
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
}, 10000);
Of course timeout it's not a solution. I was trying to find out minimal time to obtain best behavior but it's impossible. I have feeling that every browser (and version...) needs personalized time setting.
I thought that after 24-hour break I will get some brillant idea, but that doesn't work, no more ideas.
--- EDIT ---
OK, thanks for pointed mixed common js with jquery - I will correct that later.
jQuery(document).ready(function(){
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
console.log(el);
});
});
That's logical that var from should be inside ready but this still doesn't work. No effect.
If I use in loop console.log it will return for me html code of el.
--- EDIT ---
Thanks. While testing I noticed something. I wanted append element .woocommerce-Price-amount.amount to element .product-button-wrap. But how can I do that if element .product-button-wrap isn't originally in source? This object is created dynamically (I don't know how).
-- EDIT --
OK. I checked JS files and found code adding to DOM .product-button-wrap so I putted my code there and now everything works. Thanks for help.
The problem is because you're running your code before the DOM has loaded. You need to retrieve the elements within the document.ready event handler.
Also note that you have an odd mix of native JS and jQuery methods. I'd suggest using one or the other, like this:
jQuery(function($) {
$('.woocommerce-Price-amount.amount').each(function() {
$(this).parent().parent().find('.product-button-wrap').append(this);
});
});
Also note that .parent().parent() should be replace by a single call to closest(), but I can't give you an exact example of that without seeing your HTML.
i have this order form which i'm making.
Right now when someone put a coupon code I want to apply to the div of the old price a style or class (line-through) and i though I had it right...here is what i'm doing.....any suggestion why it might not be working? WARNING: I am really new to javascript....i've been working with CSS HTML but javascript is another story. Thanks!
if ($('#grand_amount_value').length > 1){
$("#Total_Amount_old_val").attr("style", "text-decoration:line-through");
}
Here is an example I threw together to show something like that working:
https://jsfiddle.net/pj6xwhcy/3/
function strikeOldAmt() {
var gav = $("#grand_amount_value");
if (gav.length > 0 && gav.text() != "" ){
// There is a GAV element and it is not empty, strike out the old amount!
$("#Total_Amount_old_val").css("text-decoration", "line-through");
}
}
Note: Using the "style" attribute would also wipe out any other custom styling you may have added. Using the css() function will not interfere if the style attribute is already set.
Assuming the page isn't reloading you could use a setInterval to check if the element exists.
var checkInterval = setInterval(function(){
if ($('#grand_amount_value').length){
$("#Total_Amount_old_val").attr("style", "text-decoration:line-through");
clearInterval(checkInterval);
}
},200);
Simplest clean way
$(document).on('change','#grand_amount_value',function(){
if ($('#grand_amount_value').val().length != 0){
$('#Total_Amount_old_val').css('text-decoration','line-through');
}
});
or if you need continuous check
$(document).on('keypress','#grand_amount_value',function(){
if ($('#grand_amount_value').val().length != 0){
$('#Total_Amount_old_val').css('text-decoration','line-through');
}
});
Here a jsfiddle
Can someone explain to me what i am doing wrong in this code?
http://jsfiddle.net/14njfqef/
var isLoggedIn = function(state){
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else(state == false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
onload=function() {
isLoggedIn(false);
}
On load i want the divs to hide but then when i click the button i want the divs to show?
Is the boolean function set out in the correct way?
Piece below tries to re-arrange piece at OP. onload not appear clearly defined , not addressed , though could be attached to an event , i.e.g., window.onload = onload . Wrapped blocks in jquery .ready() event . Removed js onclick markup from html , included at script element , or loaded from file at jquery .on("click") event . Added strict comparison operator === (an added =) to if / else if statements. Changed input type to button. Added if to else portion of composition (see link posted at comments by Felix Kling).
Try
$(function() {
var isLoggedIn = function(state){
if(state === true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else if(state === false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
};
isLoggedIn(false);
$("input[type=button]").click(function() {
isLoggedIn(true)
})
});
jsfiddle http://jsfiddle.net/guest271314/14njfqef/3/
changed your html to
<input type="submit" value="Boolean" id="toggle"/>
rewrote your js as
// JQuery run at start effectivly
$(document).ready(function() {
function isLoggedIn(state) {
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else {
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
// JQuery attaching a click event using an anonymous function
// and hard coding your isLoggedIn to true, passing variables is a bit more complicated.
$('#toggle').click(function() {isLoggedIn(true)});
isLoggedIn(false);
})
Well there's a few things I am not sure if you are aware of so I feel there's some responsibility on my end to make sure they are mentioned. They are a number of syntactical errors in your post that are stopping this from working so instead of addressing them I feel its necessary to update your view on what JQuery you are using as well as your selector choice.
First I would add a class structure to all of the div's to target them all at once so you can save on some lines of code. In production it's always better to have less code for all of your visitors to download because even a little bit of code can get out of control after enough hits on a webpage. Having to serve it kills speed and so does having to process three separate jquery selections as opposed to one.
I would change the HTML to...
<body>
<div id='content-container' class='boxes'>
Content Container
</div>
<div id='account' class='boxes'>
account
</div>
<div id='account2' class='boxes'>
account2
</div>
<input id="validateButton" type="submit" value="Boolean">
</body>
This way you can simply target all divs with $(".boxes"); ... I wouldn't recommend getting into the habbit of using $("div");
Next I would change the JQuery to being more JQuery friendly code. Its not always useful to use an onload event from pure Javascript to handle JQuery driven functions in correct time to the loading of DOM objects. Therefore you should use $( document ).ready( handler ) to handle this load event properly just in case it causes you problems down the road. The more common shorthand of this ready event is a simple $(function() { }); wrapper.
The rest of the code can be re-arranged to this....
var isLoggedIn = false; //<--Instantiate to false, make global to window level scope
//Load event Corrected For JQuery
$(function() {
$(".boxes").hide(); //<--Hide on load
//Add A Proper Updated Click Event To Button
$("#validateButton").click(function() {
isLoggedIn = true; //<--Should include real functionality not hand coded to true
checkLoginAndRespond(); //<--Validate Login Status
});
});
function checkLoginAndRespond() {
//If Logged, Show
if(isLoggedIn) {
$(".boxes").show();
//Else Don't
} else { $(".boxes").hide(); }
} //end function
Lastly, the version. New versions of JQuery have not been released for some time and seem to not be in the making so its a safe bet to use their most recent versions as it has thousands of pages of help for its syntax and it's very stable. I would recommend anything in the 2.0 or higher series JQuery.
I am assuming you have JQuery library loaded. Try
if (state) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else{
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
to solve your problem.
I have the following JQuery code which does similar functionality like Stackoverflow where the user clicks on the comment link and it displays the comments or in this case replies to a member's status update, generally it works great except when a member posts a new status update which updates the list of status updates using an ajax async postback in ASP.net MVC.
What happens is if you click on the new item in the list it brings them to a new page instead of doing what the JQuery is suppose to do.
<script type="text/javascript">
$(function() {
$("a[id ^='commentLink-']").click(function() {
match = this.id.match(/commentLink-(\d+)/);
container = $("div#commentContainer-" + match[1])
container.toggle();
if (container.is(":visible")) {
container.load($(this).attr("href"));
} else {
container.html("Loading...");
}
return false; //Prevent default action
});
});
</script>
Note: I think what is causing it is the fact that the new item in the list isn't actually on the page as the list was updated through the ajax so the new html isn't there until the page is refreshed.
Update Okay how would I use this live/event functionality that Paolo Bergantino spoke of in his answer to trigger an ASP.net MVC ActionResult?
Check out the new Events/live feature in jQuery 1.3
Binds a handler to an event (like click) for all current - and future - matched element.
So as you add new items, jQuery should add the click event to them with this.
If for some odd reason you do not want to upgrade to jQuery 1.3, you can check out the livequery plugin.
EDIT in response to update:
The actual code to use .live would be something like this:
$(function() {
$("a[id ^='commentLink-']").live('click', function(event) {
match = this.id.match(/commentLink-(\d+)/);
container = $("div#commentContainer-" + match[1])
container.toggle();
if (container.is(":visible")) {
container.load($(this).attr("href"));
} else {
container.html("Loading...");
}
event.preventDefault();
});
});
The changes that were made are mostly in the 2nd line, where
$("a[id ^='commentLink-']").click(function() {
was replaced by
$("a[id ^='commentLink-']").live('click', function(event) {
I am now also receiving the argument event to use for event.preventDefault(); which is the way you are recommended to stop events by jQuery. If return false; does the trick, though, you can keep that.
I haven't used .live yet, but I think that should do the trick. Make sure that you get jQuery 1.3 in your server before trying this, though. :)