Boiled down to the barest element, I just want to set a hidden field's value when I click an element on the page.
HTML:
<div id="toggleParent">
<input type="hidden" name="toggleValue" id="toggleValue" value="closed" />
<h2>Click Me</h2>
</div>
jQuery:
jQuery(document).ready(function() {
var toggle;
jQuery('div#toggleParent h2').click(function () {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
jQuery('div#toggleParent input#toggleValue').val(toggle);
});
});
Obviously, it's not working. (Why would I be here otherwise?) The click event is working fine, as I can step through it in Firebug. But when it gets to setting the value, the code fails. What's more, trying alert(jQuery('div#toggleParent input#toggleValue').length) returns 0. In fact, alert(jQuery('div#toggleParent h2').length) returns 0 even though the click event on that exact element just fired!
What am I missing?
This:
document.ready(function () {...});
Should be:
jQuery(document).ready(function () {...});
Or even:
jQuery(function () {...});
Or...
jQuery(function ($) { /* Use $ in here instead of jQuery */ });
Keep in mind that when using IDs, any other selector is unnecessary since IDs are unique. This is sufficient:
jQuery('#toggleValue').val(toggle);
Your 'toggle' value is undefined, you only define it in document.ready, but do not assign any value to it. To assign, use
var toggle = jQuery('div#toggleParent input#toggleValue').val();
I propose this code:
jQuery(function($) {
var toggleParent = $('#toggleParent')[0],
toggleValue = $('#toggleValue')[0];
$(toggleParent).find('h2').click(function() {
toggleValue.value = toggleValue.value === 'closed' ? 'open' : 'closed';
});
});
Try this code:
$(document).ready(function() {
var toggle;
$('div#toggleParent h2').click(function() {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
$('div#toggleParent input#toggleValue').val(toggle);
alert($("input#toggleValue").val()); // check what the new value is
});
});
Related
How can I "get" the checkbox that changed inside div "containerDIV"?
View:
#model MyModel
<div id="containerDIV">
<ul id="CheckBoxList">
#foreach (XObject t in MyModel.XCollection)
{
<li>
<input type="checkbox" value="#t.id"/>
</li>
}
</ul>
On the JavaScript (Jquery) side, I have this:
$('#containerDIV').on('change', '#CheckBoxList', function (event) {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
It's clear that $this is not the checkbox, it's the div containerDIV or checkBoxList
How can I get to the checkbox's state and value?
If your input is not being created dynamically after the DOM loads you can just call:
$('#CheckBoxList input[type=checkbox]').change(function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
or to use .on() you just need to target the input that's getting clicked:
$('#CheckBoxList').on('change', 'input[type=checkbox]', function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
FIDDLE
The way i got it to work correctly was using .is(':checked').
$('selector').change(function (e) {
// checked will equal true if checked or false otherwise
const checked = $(this).is(':checked'));
});
If you can, add the events as an attribute, like onchange='function(this);'. This returns the element to the function, so you can get data such as it's ID, or just modify it like that.
Good Luck!
Following billyonecan comment, this is another way to do it:
$('#containerDIV').on('change', '#CheckBoxList', function (event) {
var id =$(event.target).val();
if (id != null) {
//do other things
}
});
I am currently working on a "collapse all"-button for Bootstrap 3 collapsible plugin. It seems to work fine, but only if I have got only one single collapsible on my page. When I add another one, my method will still just work in the first link item.
Here ist my JS:
$(function () {
$("#toggle-all").click(function (e) {
e.preventDefault();
var $hidden = $(this).parent().data("hidden");
if ($hidden == "false") {
$(this).parent().find(".collapse.in").each(function () {
$(this).collapse("hide");
});
$(this).parent().data("hidden", "true");
} else {
$(this).parent().find(".collapse").not(".in").each(function () {
$(this).collapse("show");
});
$(this).parent().data("hidden", "false");
}
$(this).find("i").toggleClass("fa-plus fa-minus");
});
});
And here a fiddle to try: http://jsfiddle.net/rMdLZ/
Any ideas why it does not work as expected?
Thanks,
Julian
You are using 2 id's. Id's must be unique elements on each document.
See this SE question for reference: Two HTML elements with same id attribute: How bad is it really?
Change it to Classes:
$(function () {
$(".toggle-all").click(function (e) {
e.preventDefault();
var $hidden = $(this).parent().data("hidden");
if ($hidden == "false") {
$(this).parent().find(".collapse.in").each(function () {
$(this).collapse("hide");
});
$(this).parent().data("hidden", "true");
} else {
$(this).parent().find(".collapse").not(".in").each(function () {
$(this).collapse("show");
});
$(this).parent().data("hidden", "false");
}
$(this).find("i").toggleClass("fa-plus fa-minus");
});
});
http://jsfiddle.net/vP4e9/1/
Don't use ids. Use classes and I think you should do fine.
Why?
Because the ids have to be unique through out the frame.
$('#someId') will always return you the same element, but $('.someClass') will return you all elements with someClass class
I've changed $("#toggle-all").click to $(".toggle-all").click and added the toggle-all class the the collapse all buttons. And it works fine.
Demo
I've been at this problem for a while now, and I can't seem to figure it out. I have a checkbox that when checked, deletes a div containing a textbox. When that checkbox is unchecked the aforementioned textbox should return to the page. The removal works, but the append doesn't.
This is what I'm currently working with code wise:
$('#ResultsNoData1').click(function () {
var parent = document.getElementById('Results1').parentNode;
var child = document.getElementById('Results1');
if (this.checked) {
parent.removeChild(child);
}
else {
parent.appendChild(child);
}
});
My original design worked by doing the following:
$('#ResultsNoData1').click(function () {
(this.checked) ? $('.results1').hide() : $('.results1').show();
});
However the functionality I need to recreate is actually removing the data from this textbox from being accessed on the site while hiding the textbox itself at the same time. This doesn't provide that functionality.
Current example
Here you go: http://jsfiddle.net/cx96g/5/
Your issue is that you were trying to set parent inside your click, but once child is removed it would fail.
var parent = document.getElementById('Results1').parentNode;
var child = document.getElementById('Results1');
$('#ResultsNoData1').click(function () {
if (this.checked) {
node = parent.removeChild(child);
}
else {
parent.appendChild(child);
}
});
You need to show and hide that TextBox not remove.
$('#ResultsNoData1').click(function () {
if (this.checked) {
$("#Results1").hide();
}
else {
$("#Results1").show();
}
});
Working example
$('#ResultsNoData1').click(function () {
(this.checked) ? $('#Results1').val('').parent().hide() : $('#Results1').parent().show();
(this.checked) ? $('.results1casual').hide() : $('.results1casual').show();
});
JSFiddle
You are doing it right way but missing one small thing need to remove value from the textbox.
$('#ResultsNoData1').click(function () {
(this.checked) ? $('.results1').hide() : $('.results1').show().val("");
});
or
$('#ResultsNoData1').click(function () {
(this.checked) ? $('.results1').hide().val("") : $('.results1').show();
});
And this is the right way(show/hide) the textarea.
This should happen
If the user clicks on one of the two input boxes, the default value should be removed. When the user clicks elswhere on the webpage and one text field is empty, it should be filled with the default value from the data-default attribute of the spefic element.
This happens
When somebody clicks somewhere on the page and the field is empty, the field will be filled with the right value, but when somebody clicks in the field again the text isn't removed. It seems like the $(document) click event is blocking the $(".login-input") click event, because the $(".login-input") is working without the $(document) click event.
JSFiddle
A sample of my problem is provieded here: JSFiddle
Tank you for helping!
When you click on the input, the script is working, but since the input is in the document, a click on the input is a click on the document aswell. Both function will rune, document is the last one.
That is called event bubblingand you need to stop propagation :
$(document).ready(function () {
$(".login-input").click(function (e) {
e.stopPropagation()
$(this).val("");
});
});
Fiddle : http://jsfiddle.net/kLQW9/3/
That's not at all how you solve placeholders, you do it like so :
$(document).ready(function () {
$(".login-input").on({
focus: function () {
if (this.value == $(this).data('default')) this.value = '';
},
blur: function() {
if (this.value == '') this.value = $(this).data('default');
}
});
});
FIDDLE
Preferably you'd use the HTML5 placeholder attribute if really old browsers aren't an issue.
EDIT:
if you decide to do both, check support for placeholders in the browser before applying the javascript :
var i = document.createElement('input'),
hasPlaceholders = 'placeholder' in i;
if (!hasPlaceholders) {
// place the code above here, the condition will
// fail if placeholders aren't supported
}
Try below code
$(document).ready(function () {
$(".login-input").click(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").each(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
Check fiddle
Why not to use focus and blur events?
$(document).ready(function () {
$(".login-input").focus(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
http://jsfiddle.net/kLQW9/5/
P.S. In yours, and this code, on focus all data fro input will be cleared. If you need to clear only default text, add proper condition for that.
I am trying to get the class or an id of the last clicked element. This is what I have based off of what I found here...
HTML
Button
JQUERY
$('.button').click(function () {
myFuntion();
});
function myFunction (e) {
e = e || event;
$.lastClicked = e.target || e.srcElement;
var lastClickedElement = $.lastClicked;
console.log(lastClickedElement);
}
This sort of does what I want, but I am not sure how to go about modifying it so I can get just the class.
I have also tried using this solution but couldn't get it to work with my code.
$('.button').click(function () {
myFuntion();
});
function myFunction(){
var lastID;
lastID = $(this).attr("id");
console.log(lastID);
}
When I do this my console log comes back as undefined. I am probably missing something obvious. Any help is much appreciated. Thanks.
You can pass clicked element as parameter to your function:
$('.button').click(function () {
myFunction(this);
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
UPDATE added jsfiddle
A couple of ways come to mind:
$(".button").click(myFunction);
Should work with the above myFunction.
$(".button").click(function () { myFunction($(this)); });
function myFunction($elem) {
var lastID;
lastID = $elem.attr('id');
$.data('lastID', lastID);
}
In order to get the class-name of the element, assuming you have an accurate reference to the element from which you want to retrieve the data:
var lastClickedElement = $.lastClicked,
lastClickedElementClassNames = lastClickedElement.className;
This does return the full list of all the classes of the element though.
$('.button').click(function () {
myFuntion(this);
});
function myFunction(ele){
var lastID;
lastID = $(ele).attr("id");
console.log(lastID);
}
First Select all possible DOM Elements
var lastSelectedElement = null
$(document).ready(function(){
$("*").live("click",function(){
lastSelectedElement = $(this);
myFunction($(this));
});
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
than you could play with lastSelectedElement by grabbing it's ID or Class with jQuery .attr("ID OR CLASS");