Hope you can help me. How do I set the initial value of an element in Jquery/Javascript?
To explain my problem I've the following snippet.
My snippet works as I want, but only after "onclick". When I load the page, it won't get the right value. In this case I want want to when I click "show Monthly" to appear 80€ and when I click show Annual to appear 800€. But it only works after I click, not when I load the page.
Thanks
//Trying to set the initial value
$(document).ready(function() {
$(".teste").ready(function() {
var initialVal = $(this).html();
if(initialVal !== "Show Monthly"){
jQuery(".amountMonth").hide();
jQuery(".amountAnnual").show();
}else{
jQuery(".amountMonth").show();
jQuery(".amountAnnual").hide();
}
});
});
//OnClick is working right
$(document).ready(function() {
$(".teste").click(function(e) {
e.preventDefault();
var initialVal = $(this).html();
if(initialVal !== "Show Monthly"){
$(".showAnnualMonthly a").text("Show Monthly");
$(".perYearMonth").text("per year");
jQuery(".monthlyOptions").hide();
$("#arrowUpDown").removeClass("icon-up-arrow-button");
$("#arrowUpDown").addClass("icon-down-arrow-button");
jQuery(".amountMonth").hide();
jQuery(".amountAnnual").show();
}
else if (initialVal !== "Show Annual"){
$(".showAnnualMonthly a").text("Show Annual");
$(".perYearMonth").text("per month");
jQuery(".monthlyOptions").show();
$("#arrowUpDown").removeClass("icon-down-arrow-button");
$("#arrowUpDown").addClass("icon-up-arrow-button");
jQuery(".amountMonth").show();
jQuery(".amountAnnual").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="amount amountAnnual" style="display:none">Annual --> 600€</p>
<p class="amount amountMonth" style="dispay:none">Monthly--> 60€</p>
<p class="showAnnualMonthly" id="showMonthlyOpt">
<a href="" style="border:0; text-decoration:none;" class="teste">Show Monthly
<div class="row">
<span id="arrowUpDown" class="icon-down-arrow-button changeArrow" style="color: rgba(0, 161, 204, 1); margin-bottom:30px; font-size:36px;"></span>
</div>
</a>
</p>
Just run the code that shows and hides the p elements inside $(document).ready() but outside the click handler. There is no need for the first $(document).ready() function; you can combine them into one.
Related
Hello I am making a html page were there are 3 spans that the user can click on and each span can change the iframe src below. Each span is associated with its own html page and when the span is clicked it changes the iframe to its own html page.
The problem is that each html page has its own buttons with different buttons and such and in my js file I tried to add .click() to each button and for some reason the only click() works for the main iframe that is the main src of the iframe before it is changed.
Here is the HTML:
<div class="form-group">
<span id="Frame1" class="bla">test 1</span>
<span id="Frame1" class="bla">test 2</span>
<span id="Frame3" class="bla">test3</span>
</div>
<iframe src="test_1_Frame.html" style="width: 870px; height: 436px; border: 0;background-color:transparent;" id="frame">
Here is the code:
$(".bla").click(function(e) {
e.preventDefault();
$("#frame").attr("src", $(this).attr("id")+".html");
let currentFrame = $(this).attr("id");
console.log(currentFrame);
if (currentFrame == "Frame1") {
console.log(currentFrame);
} else if (currentFrame == "Frame2") {
console.log(`${currentFrame} should be Frame2`);
} else if (currentFrame == "Frame3") {
console.log(`${currentFrame} should be Frame3`);
}
});
then for the click part I did this:
$(function() {
$("#frame1_button").click(function() {
console.log('frame1');
})
$("#frame2_button").click(function() {
console.log('frame2');
})
$("#frame3_button").click(function() {
console.log('frame3');
})
});
each of these buttons is its own different button in each frame HTML. but for some reason only the "frame1" logs in the console when I press the frame1_button, but when I press the frame2 or frame 3 button nothing logs in the console.
When I go into the console and try directly typing in to click the button nothing happens(button isn't pressed) and this is the response I get:
If anyone knows why this is happening I would really appreciate your help, Thanks in advance.
(also not a big issue but I would really like to change the background colour of the currently selected span so if anyone knows how to do that I would appreciate a answer or comment).
How about this?
<div class="form-group">
<span id="Frame1" onclick=doSomething(this)>test 1</span>
<span id="Frame2" onclick=doSomething(this)>test 2</span>
<span id="Frame3" onclick=doSomething(this)>test3</span>
</div>
<script>
var doSomething = function(element){
console.log(element.id + " was clicked");
}
</script>
With a code pen here..
With onclick you can pass the element with this, and then access the id.
I'm working on a project where a button needs to be disabled until a hyperlink is clicked and a checkbox is checked. I currently have the checkbox part down using jQuery:
$('#tc-checkbox').change(function(){
if($(this).is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
But I also need to set it up so the class of tc-disable is still on the button until an anchor tag is clicked as well. I've never really done this before where a link needs to be clicked before removing a class and couldn't find what I was looking for as I was Googling for an answer.
Hope the code below helps. I also added console out put so you can track the value. Another option is use custom attribute on link element instead of javascript variable to track if the link is clicked.
var enableLinkClicked = false;
$('#tc-link').click(function() {
enableLinkClicked = true;
console.log("link clicked\ncheckbox value: " + $($('#tc-checkbox')).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($('#tc-checkbox').is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
}
});
$('#tc-checkbox').change(function() {
console.log("checkbox clicked\ncheckbox value: " + $(this).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($(this).is(":checked") && enableLinkClicked) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
#tc-btn.tc-disable {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="tc-btn">My Button</button>
<br/>
<a id="tc-link" href="javascript:void(0);">Link to enable button</a>
<br/>
<input type="checkbox" id="tc-checkbox" />
If the page is refreshing or taking you to a different page when you click the hyperlink, you will want to look into sessionStorage. When the hyperlink is clicked you will want to set a sessionStorage variable and when the page loads you want to check that variable to see if it is populated. If the variable is populated, enable the button.
Set the variable.
sessionStorage.setItem('key', 'value');
Get the variable
var data = sessionStorage.getItem('key');
If you need to re-disable the button you can clear the session storage and reapply the disabled class.
sessionStorage.clear();
You can learn more about session storage here.
If the page does not refresh you could just set an attr on the link when it is clicked like so.
$('#tc-link').on('click', function() {
$(this).attr('clicked', 'true');
});
Then when the checkbox is checked you can check this in your function.
$('#tc-checkbox').change(function(){
if($(this).is(":checked") && $('#tc-link').hasAttr('clicked')) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
These are just some solutions I could think of off the top of my head. Hope this helps.
Maybe this is better for you. First you make an .on('click' event listener on the anchor element, then, if the checkbox is checked enable the button. I added the else statement to disable the button if a user clicks the link and the checkbox is not set for an example. In this example you don't need the classes.
But if you needed to keep the the classes then you would replace the $('#tc-btn').prop('disabled', false); with $('#tc-btn').addClass() or .removeClass()
$( '#theLink' ).on( 'click', function(e)
{
e.preventDefault();
if($('#tc-checkbox').is(':checked'))
{
$('#tc-btn').prop('disabled', false);
$('#tc-btn').val('Currently enabled');
}
else
{
$('#tc-btn').val('Currently disabled');
$('#tc-btn').prop('disabled', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="tc-checkbox" />
This link will enable the button
<input type="button" id="tc-btn" value="Currently disabled" disabled="disabled"/>
Here a much more simple solution and it handles the state of the button if they uncheck the "I Accept" checkbox. It is pretty easy to implement. I just used Bootstrap to pretty up the example.
//Handles the anchor click
$("#anchor").click(() => {
$("#anchor").addClass("visited");
$("#acceptBtn").prop("disabled", buttonState());
});
//Handles the checkbox check
$("#checkBx").on("change", () => {
$("#acceptBtn").prop("disabled", buttonState());
});
//Function that checks the state and decides if the button should be enabled.
buttonState = () => {
let anchorClicked = $("#anchor").hasClass("visited");
let checkboxChecked = $("#checkBx").prop("checked") === true;
return !(anchorClicked && checkboxChecked);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
View Terms
</div>
</div>
<div class="row">
<div class="col-md-12">
<label class="form-check-label">
<input class="form-check-input" id="checkBx" type="checkbox" value="">
I accept the terms
</label>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button id="acceptBtn" class="btn btn-success" disabled="disabled">
Ok
</button>
</div>
</div>
</div>
A one-liner solution using Javascript could be:
<input type="submit" id="test" name="test" required disabled="disabled">
<label for="test">I clicked the <a target="_blank" href="https://stackoverflow.com" onclick="document.getElementById('test').disabled=false">link</a>.</label>
Change the type "submit" to "button" or "checkbox" accordingly to your needs.
I'm trying to detect which div box was clicked with JQuery and I'm not sure what I am doing wrong. I'm aware that I can approach this in a different method by directly calling functions if a div box is clicked, but I wish to do it this way by first determining what was clicked.
$(document).ready(function() {
$(document).click(function(event){
var id = event.target.id; //looks for the id of what was clicked
if (id != "myDivBox"){
callAFunction();
} else {
callSomeOtherFunction();
}
});
});
Thank you for any suggestions!
You could use the closest function to get the first ancestor element with tag div, see following example:
$(document).ready(function() {
$(document).click(function(event){
var parentDiv = $(event.target).closest("div");
console.log(parentDiv.prop("id"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<span id="span1">Test1</span>
</div>
<div id="div2">
<span id="span2">Test2</span>
</div>
I hope it helps you. Bye.
No matter what you click, you will always know the element that was clicked:
$("#myDiv").click(function(e){
alert("I was pressed by " + e.target.id);
});
Knowing that you don't want to add this to every div, and you have your click on your document, you'll need to figure out what divs can be reported as "clicked".
In order to do this you'll either need a strict hierarchy of elements in your DOM (which is anoyingly bad) or you can decorate "clickable" div's with a specific class.
Fiddle - similar to below. https://jsfiddle.net/us6968Ld/
I would use closest in Jquery to get the result you want.
$(document).ready(function() {
$(document).click(function(event){
var id = event.target.id;
var clickDiv = $(event.target).closest('div[class="clickable"]');
alert(clickDiv[0].id);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="clickable" id="clickable1">
<span id="foo"> click me - Foo - clickable 1</span>
</div>
<div id="notClickable1">
<div class="clickable" id="clickable2">
<span id="span1">
Click Me Inside Span 1 - clickable 2
</span>
</div>
<div class="clickable" id="clickable3">
<div id="notClickable2">
<div id="notClickable3">
<span id="click me">Click Me - clickable 3</span>
</div>
</div>
</div>
</div>
try this:
$('div').click(function() {
alert($(this).attr('id'));
});
https://jsfiddle.net/1ct0kv55/1/
When i click on second item with slideToggle, first item close.
$(function() {
$('.toggleSitemap').find('ul').css('display','none')
$('.toggleSitemap').click(function(){
$(this).parent().find('ul').slideToggle('slow');
});
});
http://jsfiddle.net/qHZsZ/2/
I dont know how much will this help you. I also needed to implement accordian(toggle) in my MVC project once, and I used something like this:
View.aspx:
<div class='toggle' style="float: left">
<div style="float: left;clear:both;">
<br />
<span class="ulGroup" jqattr="<%:Group.Key %>" style="font-weight: bold;font-color: black;cursor: pointer"><img src="<%: Url.Content("~/Images/imageplus.gif")%>"/>
<%:Group.Key%></span>
</div>
<div class="togglebox" style="clear:both;" >
<!-- Write contents as you wish -->
<!-- as
<ul> test
<li>Test1></li>
<li>Test2></li>
<li>Test3></li>
</ul>
.
.
.
-->
</div>
</div>
And called a design.js (javascript file) as :
$(document).ready(function () {
//Hide the tooglebox when page load
$(".togglebox").hide();
//slide up and down when click over span
$(".ulGroup").click(function () {
var valueText = $(this).attr('jqAttr');
// slide toggle effect set to slow you can set it to fast too.
var x = $(this).parent().next(".togglebox").css("display");
if (x == "block") {
$(this).text('');
$(this).append($('<img src="../../Images/imageplus.gif"/>'))
$(this).append(' ' + valueText);
}
else {
$(this).text('');
$(this).append($('<img src="../../Images/imageplus.gif"/>'))
$(this).append(' ' + valueText);
}
$(this).parent().next(".togglebox").slideToggle("fast");
return true;
});
});
You're pretty close. I think the key ingredient you're missing is to prevent propagation of the click event.
Also, to make it a little less quirky, you only want the click event to fire if the target's direct parent has the toggleSitemap class.
$(function() {
$('.toggleSitemap').click(function(e){
if ($(e.target).parent().hasClass('toggleSitemap')) {
e.stopPropagation();
$(this).children('ul').slideToggle('slow');
}
});
});
Here's an example: http://jsfiddle.net/DkbNA/2/
By Sharepoint a bunch of tds get generated with a few elements inside of them. So just to be clear I cant edit or change elements since it gets generated.
What I want to accomplish is to iterate throught all '.js-contentFollowing-itemLink' and then if the .text() contains the specific text I am looking for the '<span> Stop following</span>' should become hidden with '.hide()'.
I cant seem to accomplish this I have tried many ways.
Here is the jsfiddle:
http://jsfiddle.net/QXwyk/3/
Also take notice that I cant grab a id that is unique and many of these elements are generated with different values and texts.
HTML:
<span class="ms-contentFollowing-itemTitle">
test
</span>
<br>
<div class="js-contentFollowing-itemUrlDiv">
<span class="ms-metadata ms-contentFollowing-itemUrl"></span>
<input type="text" readonly="readonly" class="ms-metadata ms-contentFollowing-itemUrl ms-contentFollowing-itemFullUrl" style="visibility: visible; border-color: transparent; background-color: transparent;">
</div>
<span>Stop following</span>
My JS:
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test")
$(this).closest("span").hide();
});
Note: I know it hides wrong element but the If statement works its the code inside the if statement that I cant accomplish I need to hide ' Stop following'. This JS is just one of the examples I have done that is not working.
I tried with $('.ms-secondaryCommandLink span').hide(); inside the if statement but that removed all <span> with "Stop following" :/
Thanks a bunch!
Several issues in your code:
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test")
var text = $(this).parent().parent().parent().hide); <-- hide not closed properly
} <--- Extra bracket here..
});
Working code:
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test") {
var text = $(this).parent().parent().parent().hide();
}
});
Html
<div class="ms-content">
<span class="ms-contentFollowing-itemTitle">
test
</span>
<br>
<div class="js-contentFollowing-itemUrlDiv" id="contentFollowingUrl_18" url="http://dev/socialsites/Utförsåkning">
<span class="ms-metadata ms-contentFollowing-itemUrl"></span>
<input type="text" readonly="readonly" class="ms-metadata ms-contentFollowing-itemUrl ms-contentFollowing-itemFullUrl" style="visibility: visible; border-color: transparent; background-color: transparent;">
</div>
<span>Stop following</span>
</div>
JS
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test")
var text = $(this).closest('.ms-content').find('.ms-secondaryCommandLink').hide();
});
http://jsfiddle.net/QXwyk/4/
You can select the object containing specific text by following way,based on which you can can do remaining actions ...
Example: $('.js-contentFollowing-itemLink:contains(test)').hide(); will hide "test"