I can't get jQuery to work with Bootstrap buttons - javascript

Put simply: my goal is to have two buttons on a page, so that "1" is displayed when the first is pressed, and "2" is displayed when the second is pressed. This works with radio input, but when I add a button label from Twitter Bootstrap, it no longer works.
First, here is the jquery I am using. I am trying to change the value of the span to the value of the button pressed:
<span id="val">0</span>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function() {
$('input[type=radio]').click(function() {
$("#val").html($(this).val());
});
});
</script>
It works fine with this:
<input type="radio" Id="Radio1" value="1" name="a">
<input type="radio" Id="Radio2" value="2" name="a">
But when I do this, it no longer works (I can see and press the buttons, but the value of span remains at 0):
<div class="btn-group" data-toggle="buttons">
<label type="button" for="Radio1" class="btn btn-primary active">
<input type="radio" Id="Radio1" value="1" checked>
</label>
<label type="button" for="Radio2" class="btn btn-primary">
<input type="radio" Id="Radio2" value="2">
</label>
</div>
It seems to me like the label tags are causing a problem, but I am unsure why. Removing the labels makes it work, but I need the button labels.

Place the click event on labels, then find the value on its "input" children:
$(function() {
$('div.btn-group label').click(function() {
$("#val").html($(this).children('input').val());
});
});
JsFiddle: https://jsfiddle.net/5vh3yzzq/1/

Related

How to validate bootstrap radio buttons

I am trying to validate this section of the form but whichever button is selected, option1 returns false. How can I get each radio to have different values when they are active/inactive or alternatively get a value from the button-group?
$(function register(){
$('.err').hide();
$("#submit").click(function() {
if ($('#option1').prop("checked", false)){
$("#fcerr").show();
}
if ($('#option1').prop("checked")){
$("#fcerr").hide();
}
});
});
<div class="btn-group btn-group-justified btn-group-sm" data-toggle="buttons">
<label id="lopt1" class="btn btn-primary">
<input type="radio" name="option1" id="option1" autocomplete="off"> Staff
</label>
<label id="lopt2" class="btn btn-primary">
<input type="radio" name="option2" id="option2" autocomplete="off"> Client
</label>
</div>
<div><label class="err" id="fcerr">Error Message</label></div>
<input name="register" type="submit" value="Register" class="btn btn-primary btn-lg btn-block" id="submit">
I have also tried getting the values of the radio boxes but they are always "on" regardless of which radio is active.
var client = $("#option2").val();
alert(client);
With your code:
if ($('#option1').prop("checked", false)){
$("#fcerr").show();
}
You are actually setting the property "checked" to be false, everytime. After that is done the if statement recieves a truthy value so it will execute what's inside the if block.
Try your validation like this instead:
if($('#option1').is(':checked')){
//...
}
Also, if you want your inputs to actually behave as a group (meaning only one can be checked at a given time) you have to share the same name attribute, you can update your html to:
<label id="lopt1" class="btn btn-primary">
<input type="radio" name="myOptions" id="option1" autocomplete="off"> Staff
</label>
<label id="lopt2" class="btn btn-primary">
<input type="radio" name="myOptions" id="option2" autocomplete="off"> Client
</label>
A few things:
You didn't include a javascript framework in your code snippet, though your question is tagged with jQuery.
The 4th line if ($('#option1').prop("checked", false)){ is changing the value that you're trying to evaluate.
The option elements should share the same name attribute if you want to treat them as a group that can be validated

prop('checked', true) doesn't seem to work with input type radio

When I click a button. I show a view with Active status checked. But the code isn't working.
I'm unable to find the mistake here. Could someone help me out?
No matter what I try, the radio buttons are always unchecked when I call the function on button click.
My Code:
$(function(){
$('#btn').click(function() {
$('#name').val('');
$('#active').prop('checked', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="radio" class="flat" id="active" name="status" value="true"> Active
<input type="radio" class="flat" id="inactive" name="status" value="false"> Inactive
</div>
<button type="button" id="btn" class="btn btn-success" >Add</button>
I was using bootstrap. I removed class="flat" from input type. Now it's working, but I lost the styling.

How to change elements(img's) position via radio buttons?

I got an image positioned in container and 3 radio buttons. I would like to add another images appear over the container main image when some of the radio buttons is chosen. Each of the buttons will have different positions of the images shown when they are active.
So far I got that:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" id="q156" name="quality[25]" value="1" /> 1
</label>
<label class="btn btn-default">
<input type="radio" id="q157" name="quality[25]" value="2" /> 2
</label>
<label class="btn btn-default">
<input type="radio" id="q158" name="quality[25]" value="3" /> 3
</label>
</div>
</div>
</div>
<div class="col-md-8 col-fl">
<div id="img_box">
<img style="width: 100%;" src="img/other/rounded_corners.png" />
</div>
You could add the image sources as data attr. to the radio button.
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" id="q156" name="quality[25]" value="1" data-img="http://placehold.it/350x150/ff0000" /> 1
</label>
<label class="btn btn-default">
<input type="radio" id="q157" name="quality[25]" value="2" data-img="http://placehold.it/350x150/00ff00"/> 2
</label>
<label class="btn btn-default">
<input type="radio" id="q158" name="quality[25]" value="3" data-img="http://placehold.it/350x150/0000ff" /> 3
</label>
</div>
<div class="col-md-8 col-fl">
<div id="img_box"></div>
The img box is empty but size and image are set by css:
#img_box{
width: 350px;
height: 150px;
background: url('http://placehold.it/350x150/ff0000')
}
Then add a event that append a img overlay on click (using source from radio buttons):
$(function(){
$('input[type=radio]').click(function(){
$this = $(this)
$img_box = $('#img_box')
$overlay = $('<img/>').attr('src',$this.data('img'))
$img_box.html('').append($overlay)
});
})
See this example: https://jsfiddle.net/fmytsjv7/1/
You can achieve that using jQuery, and binding event handler to your radio buttons.
Like this one:
$('input:radio[name="quality[25]"]').change(function(){ });
Then add the handler to alter the attributes/css properties of the target image container or the image element directly.
You can use jQuery .css() to alter css properties of your target element
Like:
$("#img_box").css({"height":"100px","width":"100px",background:"red"});
While, you can use jQuery .attr() to alter the attributes of your target element.
Like: (in this case its the img's "src" attribute)
$("#img_box > img").attr("src","path/to/whatever/image");
HERE'S A SAMPLE IN JSFIDDLE
I see that you included jQuery tag in your question, so I assume you are interested in jQuery based solution.

PrintThis Not Capturing Checked Checkboxes

So I am using the PrintThis JQuery plugin in order to print a form field, but for some reason I am unable to have the plugin print out any changes made to the checkboxes. When I click "Print", the only checkbox that appears to change is one that has a "checked" property by default. Any ideas on how to fix this?
HTML:
<body>
<div id="print">
<form>
<input id="option" type="checkbox" checked>
<label class="checkbox" for="option"> You are 18 years or older</label>
<br><br>
<input id="option2" type="checkbox">
<label class="checkbox" for="option2"> You have tested positive for something in your blood</label>
<br><br>
<input id="option3" type="checkbox">
<label class="checkbox" for="option3"> You have health-related kidney problems</label>
<br><br>
<input id="option4" type="checkbox">
<label class="checkbox" for="option4"> You have health-related skin problems</label>
<br><br>
<input id="option5" type="checkbox">
<label class="checkbox" for="option5"> You have a low platelet count</label>
</form>
</div>
<br>
<br>
<input id="printButton" type="button" value="Click here to download and print this checklist to review with your doctor." />
</body>
JSFiddle: http://jsfiddle.net/Hybridx24/bxtpv26x/
Not sure what the problem might be here, but you can get around it by explicitly setting the checked attribute for the checkboxes that are checked.
$("input:button").click(function () {
$('input[type="checkbox"]').each(function() {
var $this = $(this);
if($this.is(':checked')) {
$this.attr('checked', true);
} else {
$this.removeAttr('checked');
}
});
$("#print").printThis({'importStyle': true});
});
Check Fiddle
So after skimming through the plugin's source. Looks like there's a property for form values. I added it in and it seems to work.
$('#selector').printThis({formValues:true});
http://jsfiddle.net/wzp0e9r9/

jQuery Serialize working intermittently with Bootstrap radio button group

I'm trying to serialize a radio-button when the Bootstrap .btn label is clicked.
HTML:
<div class="btn-group" data-toggle="buttons">
<label label-default="" class="btn btn-primary">
<input id="option1" name="options" type="radio" value="1">Option 1</label>
<label label-default="" class="btn btn-primary active">
<input id="option2" name="options" type="radio" value="1">Option 2</label>
<label label-default="" class="btn btn-primary">
<input id="option3" name="options" type="radio" value="1">Option 3</label>
</div>
jQuery:
$(".btn").on('click', function(){
console.log("Name: " + $(this).children('input').attr('name') );
console.log("Value: " + $(this).children('input').val() );
console.log("Serialized: " + $(this).children('input').serialize() );
})
The name and value are always present in my output but the serialization works intermittently (sometimes returning the serialzed value and sometimes returing an empty string) and I can't figure out why.
Demo here: http://www.bootply.com/86422#
Thanks!
You should really read ALL of the documentation on jQuery's .serialize() function if you are having issues.
From the .serialize() API :
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Now from W3's documentation on successful controls :
For radio buttons that share the same value of the name attribute, only the "on" radio button may be successful.
All of that explains exactly why it works intermittently. Because sometimes you happen to check the radio button so it is considered "on" and your function serializes that input button.
Here is a workaround :
Instead of using a input of type radio button, just use a plain input and set the display to none.
<div id="mode-group" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input name="mode" id="option1" value="cash/check" style="display: none">Cash / Cheque / Bank Transfer</label>
<label class="btn btn-primary">
<input name="mode" id="option2" value="jobsBuddy" style="display: none">JobsBuddy Disbursement</label>
</div>
Bootply Demo
jQuery .serialize() and .serializeArray() will only parse buttons which are checked. These are known as "successful controls", as mentioned in the jQuery documentation.
If you'd like to use a Bootstrap button group where all buttons are unchecked (as seen in your question), then you should consider "What if a user never checks any of the buttons?".
Therefore, you should include a hidden button which is checked by default, so that at least one of the buttons in your button group is parsed by .serialize() or .serializeArray().
<form>
<div class="form-group">
<!--
This hidden checked button (with value 'none')
will ensure that `serialize` parses at least one
input in the button group.
-->
<input class="hidden" type="radio" name="color" value="none" checked>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" name="color" value="blue" />
<span>Blue</span>
</label>
<label class="btn btn-default">
<input type="radio" name="color" value="green" />
<span>Green</span>
</label>
</div>
</div>
</form>

Categories