Radio button inside anchor element is reset after jQuery click handler - javascript

I have a situation where an element, of type radio, is contained in an element. The anchor element has a href but I want to override that behaviour by adding a jQuery 'click' handler to the element.
The click handler makes the radio button inside it the selected one within the group. This all works when the anchor is clicked, however, when the radio button is clicked it appears that jQuery resets the selected radio to the previously selected one!
Here is a the simplified page that duplicates the issue:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#a1").click(function(event) {
anchorClicked("a1");
return false;
});
$("#a2").click(function(event) {
anchorClicked("a2");
return false;
});
});
function anchorClicked(anchorId) {
$('#' + anchorId + ' input:radio').attr("checked", true);
alert("Look at what is selected and what happens after the event when this dialog is closed!");
}
</script>
</head>
<body>
<form>
<ul>
<li id="li1">
<a id="a1" href="javascript:alert('default functionality')">
<input value="1" name="rb" type="radio" id="rb1">
<span>Details 1</span>
</a>
</li>
<li id="li2">
<a id="a2" href="javascript:alert('default functionality')">
<input value="2" name="rb" type="radio" id="rb2">
<span>Details 2</span>
</a>
</li>
</ul>
</form>
</body>
Does anyone have any idea how I can prevent jQuery for resetting the radio button?

<script type="text/javascript">
$(document).ready(function() {
$("input:radio").click(function(event){event.stopPropagation();});
});

This is a slightly strange way of doing things. You can get the effect you are after by first using a label element instead of the span like so:
<label><input value="1" name="rb" type="radio" id="rb1" /> Details One</label>
<label><input value="2" name="rb" type="radio" id="rb2" /> Details Two</label>
By doing this clicking anywhere in the label element will select the radio button.
From there you should watch for a change event on the radio buttons if you want to:
$('input:radio[name="rb"]').change(function() {
if (this.checked) {
alert('remember the deselected radio button changes also');
}
});

The easiest way I've found to solve this issue is to remove the href attribute from the anchor element during the click event:
$("#a1").click(function(event) {
this.removeAttribute("href");
anchorClicked("a1");
});
This means I no longer need to return false to prevent the default behaviour and the event can bubble up the DOM safely and everything then works.

The problem is that your "return false" to cancel the default anchor tag behaviour is also cancelling the behaviour of the clicking on the radio button so it sets it back to what it was originally, regardless of the actions of the click event. Setting the fucntions to return true exhibits the expected behaviour (as well as the default click function).
To fix it finally you want to get rid of the default click event completely. To do this you could very simply change the href to "#" so that it doesn't do much when actioned. See http://jsfiddle.net/FrcRx/1/ for an example of this in action.
the best way to do it would be to remove the href attribute completely. This of course makes most browsers not consider it a link so you would need to apply appropriate styling yourself to make them look like links still.
This is done with the removeAttr jquery function and the addClass function. See a demo of it here: http://jsfiddle.net/FrcRx/2/

$('input:radio').click(function(e) {
e.stopPropagation();
});
$('a[id^="a"]').click(function(e) {
$('input:radio:first', this).attr("checked", true);
return false;
});
The important part is stopping propagation of the click event when the radio button is clicked. However it seems that if you return false then the radio button is not select as you would expect it to be.
Next we bind the click event to any a tag which has an id starting with the letter "a". When clicked the first radio button input inside of the a tag is selected and then checked.
DEMO: http://jsfiddle.net/marcuswhybrow/mg66T/2/

Related

How to re-disable (disable) the text box on clicking a button or a link?

I have a script that enables the disabled text box when clicking on a button. But, I just don't know how to re-disable the text box again.
The coding is below.
HTML:
<div class="input-group">
<label for="some-tbox" class="input-group-addon">Label:</label>
<input id="some-tbox" type="text" class="input-box" value="some value" disabled>
<span class="input-group-btn">
<button class="enable" type="button">button</button>
</span>
</div>
JS:
$(".enable").click(function(){
$(this).parent().parent().children(".input-box").removeAttr("disabled");
$(this).toggleClass("disable");
$(this).toggleClass("enable");
});
$(".disable").click(function(){
$(this).toggleClass("enable");
$(this).toggleClass("disable");
$(this).parent().parent().children(".input-box").attr("disabled", "disabled");
});
And I have made a fiddle out of it. But, It's not working. Here is the link.
Instead of messing with adding and removing classes, just toggle the disabled property with:
$(".enable").click(function() {
$(this).closest('.input-group').find('input').prop('disabled', !$(this).closest('.input-group').find('input').prop('disabled'))
});
jsFiddle example
The problem is this line $(".disable").click(function(){ ...})
You are binding a click event handler to a class named disabled which was not available initially during page load, it appears dynamically later.
You need to delegate the event handler to some parent which always exist and then handle the event there, in this case you can do this:
$(".input-group").on('click', '.disable', function(){
$(this).toggleClass("enable");
$(this).toggleClass("disable");
$(this).parent().parent().children(".input-box").attr("disabled", "disabled");
});
jQuery's on function
You cann't bind an element ".disable" that don't exist , In that case you can rebind it when you changed it's class. Code behind may help you:
$(".enable").on("click",enabledClick)
function enabledClick (argument) {
$(".enable").parent().parent().children(".input-box").removeAttr("disabled");
$(".enable").toggleClass("disable");
$(".enable").toggleClass("enable");
$(".disable").on("click",disabledClick)
}
function disabledClick (argument) {
$(".disable").parent().parent().children(".input-box").attr("disabled", "");
$(".disable").toggleClass("enable");
$(".disable").toggleClass("disable");
$(".enable").on("click",enabledClick)
}

Show Interactive Html elements on top of an anchor tag

I have a area surrounded by an anchor tag and it should be directed to anchor tag href wherever user clicks on that area. And also that area should contain a textbox and button control which should allow user to type some text and submit. The problem is when I click on the textbox or button it does a redirect to the page given in anchor tag.
<a href="http://stackoverflow.com/">
<div style="border:1px solid grey;width:300px;height:100px;">
<div style="">Title</div>
<div>
<input type="text" name="name">
<button type="button" onclick="alert('button clicked');">Click Me!</button>
</div>
</div>
</a>
Please refer this jsfiddle.
I have created a simplified problem here.
However I found a solution for this by giving negative margin-top values. It is working but I am interested in a better solution. Because this solution is not scalable since the button and textbox are not inside the content div.
Each of these sections represent a item in a search result. When a user click on a search item it would navigate to single item page. At the same time users should be able to edit content from search results view by selecting edit option. When they select edit, a textbox and a button to submit should appear.
Unfortunately the HTML5 spec says about the <a> element:
Content model:
Transparent, but there must be no interactive content descendant.
What that means is, an <a> element is allowed to contain any elements that its parent is allowed to contain, except for things like <button>.
You'll need to find a way to get your <button> and <input> working outside of the <a>
Use this
<input type="text" name="name" onclick="return false;" />
Use this only if you don't want to change your markup.
The best solution is go with the semantics of HTML and style it. This way is not correct as Gareth pointed out.
In the case of your button
<button type="button" onclick="buttonClick(event);">Click Me!</button>
function buttonClick(e) {
alert('button clicked');
e.preventDefault();
}
Introduce a onclick for textfield and use stoppropagation method for a event. for ex ,
textfield.onclick = function(e) {
e.stopPropagation();
}
Another alternate is to use <div onclick="function()"> instead of <a> tag for what you think to achieve

Alert navigates to Homepage when using jQuery Mobile

I currently have a button that when clicked it passed that buttons id to a function and the function alerts this id name. Now the alert displays the right name but when I click okay on the alert it takes me back to the homepage. Here is the code:
JS:
function ButtonPicture(id)
{
alert(id);
}
HTML:
<input type="submit" onclick="ButtonPicture(this.id);" id="car1" value="Take Picture">
I'm not sure why this is happening and how to prevent this
You have attached your function to a submit input element. By default, when you click a submit button, the browser will submit a form attached to it, which, will redirect the page to the action specified of the form. If no action is specified, it will redirect to the current page.
You need to prevent the default action here. You have many options, but I present two common options below:
Option 1: Unobtrusively bind the click event, and preventDefault:
JQuery
$(document).ready(function() {
$("#car1").click(function(e) {
e.preventDefault();
ButtonPicture(this.id);
});
});
Notice: You don't need to wrap this in $(document).ready(function() { }); if you place this code after your input element in the document.
HTML
<input type="submit" id="car1" value="Take Picture">
Option 2: Return false
You can return false from the onclick event:
<input type="submit" onclick="ButtonPicture(this.id); return false;" id="car1" value="Take Picture">
My personal preference and recommendation would be option 1

How do I make this Javascript checkbox trigger action work like my CSS only example

I'm using the following code to test for "if" a checkbox is checked on page load.
If it is, then a certain additional field will be shown (called myfield):
<style>
#myfield {
display: none;
}
</style>
<input type="checkbox" id="mycheckbox" name="mycheckbox" />
<input type='text' id='myfield' name='myfield' />
<script>
if ($("#mycheckbox").is(":checked")) {
document.getElementById("id").style.display="block";
}
</script>
However, this only works when the page loads and the checkbox is already checked. It doesn't work live when the box isn't checked on page load, and you go to click the box. I want the hidden field to show up right away when the box is "checked" without the page having to reload. I then want myfield to hide right away when the box is unchecked.
Can any anyone point out the better/proper way to do this?
Additionally:
Of note: I do know how to do this in CSS using labels, but I need to use javascript other times.
Here's what works fine in modern browsers using just CSS: http://jsfiddle.net/3KTC3/
Here's that CSS only jsfiddle code:
<style type="text/css">
.label-for-check {
display:none;
}
.check-with-label:checked + .label-for-check {
display:block;
}
</style>
<div>
<input type="checkbox" id="check" class="check-with-label" />
<label for="check" class="label-for-check">
<br /><br />MyField<br />
<input type='text' id='myfield' name='myfield' size='10' />
</label>
<div>
You need to attach a change event handler. Your posted code only executes when page is loaded, it doesn't watch over your element's state.
Here's a jQuery equivalent to your CSS version with classes and adjacent selector:
$('.check-with-label').change(function() {
$(this).next().toggle(this.checked);
}).change();
Fiddle
Explanation: this references the checkbox being clicked, get the next element (equivalent to your CSS + selector) and toggle its display based on the checked state of the checkbox.
Another version that works only with your 2 given IDs:
$('#mycheckbox').change(function() {
$('#myfield').toggle(this.checked);
}).change();
Fiddle
Note that your CSS version is compatible with all desktop browsers including IE7 and above. Consider whether it is necessary to use JS for this.
edit: You have to trigger the change handler after attaching it, so if the checkbox is already checked when the page is loaded, the triggered handler will display the field.
Your problem is that jQuery will only check one time (when you load the site) if your checkbox is checked.
The change handler will fire every time the user changes the checkbox, if it is cheked it will show #myfield
Do something like this:
$('#mycheckbox').change(function() {
if ($(this).is(":checked")) {
$('#myfield').show()
}
});
$(document).ready(function(){
if($("#mycheckbox").is(":checked")) $('#myfield').show();
$('#mycheckbox').on('change', function(){
if($(this).is(":checked")) {
$('#myfield').show();
} else {
$('#myfield').hide();
}
})
});

JQuery Custom Image From Checkbox to Radio

I am using the following code to make a custom checkbox with my own images and it works but it's using a Checkbox and I need to use Radio buttons.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#moreinfo").change(function() {
if(this.checked) {
$(this).prev().attr("src", "checkbox_unchecked.gif");
} else {
$(this).prev().attr("src", "checkbox_checked.gif");
}
});
});
</script>
Next...here's the HTML:
<label for="moreinfo">
<img src="checkbox_unchecked.gif"/>
<input name="moreinfo" type="checkbox" id="moreinfo" style="display:none">
</label>
If it a question of changing from checkbox to radio type or does the jquery need changing too?
How do I go about this?
Change the type="checkbox" to type="radio" (and add some more radio buttons for testing, grouping them via the name attribute, they may not have the same id as IDs are unique!). Then, you also need to handle the click event of the replacement images.
But actually, that's going beyond your original question, which you could have solved by simply trying it out. ;)
A Radio Button uses also the attribute checked. So you can switch the element without changing the script (perhaps the gifs).
But your script will never run, because your checkbox/radio button is not displayed.
So you need some functionality to change the status when clicking the image.

Categories

Resources