Highlight Specific Button Upon Page Load - javascript

I'm building a quiz app, and for a certain part of it I would like for some of the answers to be highlighted upon loading of the page.
These are the buttons:
<input type="hidden" name="correct_answer" value="<?php echo (isset($correct_answer)) ? $correct_answer : 'no corect answer';?>">
<button name="answer" value="A" class="btn btn-primary btn-lg">A</button>
<button name="answer" value="B" class="btn btn-primary btn-lg">B</button>
<button name="answer" value="C" class="btn btn-primary btn-lg">C</button>
<button name="answer" value="D" class="btn btn-primary btn-lg">D</button>
<button name="answer" value="E" class="btn btn-primary btn-lg">E</button>
You can see I'm loading a hidden element with the correct answer inside it.
All the back end works just fine, But I can't seem to figure out how to do this.
Is it possible to do this in native JS or is jQuery a must?
Also, how do I go about doing this? How do I make sure the CSS class is added to the right element?
EDIT:
This is the code I ended up using:
<script type="text/javascript">
document.getElementById("<?php echo $correct_answer;?>").style.backgroundColor = "green";
</script>

You can do this with vanila javascript using the backgroundColor,
So your js code would look like:
document.getElementById("answer1").style.backgroundColor = "red";
Working Fiddle
Please note that I have set Id for one element, however you can set for all elements and use that Id whose background is to be changed.

Since you're already rendering the page with PHP, why not just have it add a class to those elements you want highlighted.
<button name="answer" value="A" class="btn btn-primary btn-lg <?php if ($correct_answer === "A") { ?>highlight<?php } ?>">A</button>
Then style that class:
.highlight {
background-color: red;
}
Even if you were to use javascript to solve this, adding a class is far better than adding styles to an element. The class is more semantic and can be easily restyled without having to dig through your code.

Here's a pure JavaScript solution that will work with your existing HTML:
var correct= document.getElementsByName('correct_answer')[0].value;
var buttons= document.getElementsByName('answer');
for(var i = 0 ; i < buttons.length ; i++) {
if(buttons[i].value===correct) {
buttons[i].style.background= 'red';
break;
}
}
Fiddle at http://jsfiddle.net/qw7qhvnq/

Related

Timer for javascript button selection

The below code generates a json string on the click of some buttons.
<div id="btnStudios" >
<button type="button" id="01" value="warner" class="btn btn-default">Warner</button>
<button type="button" id="02" value="tf1" class="btn btn-default">TF1</button>
<button type="button" id="03" value="gaumont" class="btn btn-default">Gaumont</button>
<button type="button" id="04" value="pathe" class="btn btn-default">Pathe</button>
<button type="button" id="05" value="studiocanal" class="btn btn-default">StudioCanal</button>
<button type="button" id="06" value="francetv" class="btn btn-default">FranceTV</button>
<button type="button" id="07" value="m6snd" class="btn btn-default">M6SND</button>
</div>
var output = $(".btn").click(function() {
$(this).toggleClass('active');
var output = {
Studios: $('#btnStudios button.active').map(function() {
return $(this).val();
}).get(),
};
if (!output.Studios.length) {
output.Studios = $('#btnStudios button').map(function() {
return $(this).val();
}).get()
$('.list').html(JSON.stringify(output));
});
Basically what i am looking for is a timer which refreshes for 1 second everytime a button is clicked and then generates the json string based on the button selection.
I used the setInterval() function but that did not help.
How would i go about this?
Thanks in advance.
I didn't fully understand your question.
However, based on the code, I assume you want to show a JSON-string based on which buttons have the .active class?
Your code contained syntax errors.
I created a quick JSfiddle with what I think you wanted.
However, I have made no use of setTimeout since I couldn't come up with valid use case.
Feel free to provide us with more info and I'll improve my answer!
EDIT:
Okay, so you want to wait 1sec after the click.
I updated the JSfiddle.
EDIT²:
I'd also use clearTimeout so clicks that happened while you are already waiting 1 sec are ignored.
As seen in this JSfiddle.

function javascript for both active label.hasClass

I have a big problem: I have basically two label
 
<label id="label1" class="btn btn-transparent grey-salsa btn-circle btn-sm label1 active" onclick="showSomething($(this));">
<input type="radio" name="options" class="toggle" id="Radio2" />Label1</label>
<label id="label2" class="btn btn-transparent grey-salsa btn-circle btn-sm label2" onclick="showSomething($(this));">
<input type="radio" name="options" class="toggle" id="Radio3" />Label2</label>
 
and the javascript function showSomething
I have to Show 3 graphics and the problem is that. I want to show one of the graph when two label are activated so the both label should be active
and so I do this:
function showSomething (labelJQ) {
    if (labelJQ.hasClass ('active'))
        return;
    else {
        if (labelJQ.hasClass('label1')) {
            if (labelJQ.hasClass('label2')) {
                $('#Chart1').hide();
                $('#Chart2').hide();
                $('#Chart1,2').show();
            }
}
}
}
but does not give me any results, does not know label.hasClass for both at the same time if I do one and then the other works perfectly but to me I do not need so - is there a way that can I do?
I have tried to interpret your question, so please provide further clarification if this does not do what you had hoped for, but...
I think your jQuery is a significant part of the issue here. I believe it is clearer if you assign the click change handler in a way similar to the following:
$('input[type=radio]').change(function() {
$('.chart').hide();
if (this.id == 'option1') {
$('#chart1').show();
} else if (this.id == 'option2') {
$('#chart2').show();
}
});
I have put together a demo from your original input here:
https://jsfiddle.net/g8wkwdo4/2/
Hope that helps!

how to find the last dynamic button clicked

I have created a dynamic buttons each button is the same:
<input type="button" id="editBtn" value="Edit" style="float: right" />//each button has its id ofcourse
When one button is pressed it shows a table.
I am looking for a way to 'click last button'/'hide the table' if an other button on page is clicked.
Using Jquery, is it possible ? or is there a better way to do it?
If u want to display content using button(hide/show)
You can accomplish this using jquery toogle function
$(document).ready(function()
{
$("#button").click(function()
{
$("#table").toggle();
});
});
link to fiddle
Simply hide all siblings of the selected table...
So for example, if you have (Pseudo code)
<input type="button" id="editBtn1" value="Edit" onclick="showTable(1)" />
<input type="button" id="editBtn2" value="Edit" onclick="showTable(2)" />
<input type="button" id="editBtn3" value="Edit" onclick="showTable(3)" />
<table id="table1">...</table>
<table id="table2">...</table>
<table id="table3">...</table>
JS would be :
function showTable(tableid) {
$("#table" + tableid).show().siblings().hide();
}
But of course, this is all very hard coded & hence an avoidable practice.
Or as discussed in comments :
function showTable() {
var tableId = $(this).index();
$("table").hide().eq(tableId).show();
}
I think this is what you want: http://jsfiddle.net/BY27P/9/
This will remember the tables you have viewed and let you view all previous ones using basic JavaScript array push/pop.
Here is the JavaScript (view fiddle for full code):
var viewedTableHistory = [];
hideAllTables=function(){
$('table[id^="table"]').hide(); //hide all tables
}
loadTable=function(id){
viewedTableHistory.push(id);
$('#history').text(viewedTableHistory);
hideAllTables();
showCurrentTable();
};
hideCurrentTable=function()
{
$('#table'+viewedTableHistory[viewedTableHistory.length-1]).hide();
};
showCurrentTable=function()
{
$('#table'+viewedTableHistory[viewedTableHistory.length-1]).show();
};
viewPrevTable=function()
{
hideAllTables();
viewedTableHistory.pop();
$('#history').text(viewedTableHistory);
if(viewedTableHistory.length===0) alert('You are back to the beginning.');
showCurrentTable();
};
I think I solved your problem try this fiddle ...
See output on below fiddle
Js fiddle
Style:
.tbl{
display:none;
}
Jquery:
$(".btn").click(function(){
var $this = $(this).next("table");
$( this ).next("table").removeClass("tbl");
$(".btn").next("table").not($this).addClass("tbl");
});
Html:
<div class="tble">
<input type="button" value="Button1" class="btn"/>
<table class="tbl"><tr><td>test1</td></tr></table>
</div>
<div class="tble">
<input type="button" value="Button2" class="btn" />
<table class="tbl"><tr><td>test2</td></tr></table>
</div>

Getting active buttons in button-group (bootstrap)

I have a button group and am willing to update some other field on change according to the active buttons.
See the jsfiddle here
This is the HTML, copied from the documentation:
<div class="btn-group arrActiviteit arrUpdate" data-toggle="buttons">
<label class="btn btn-primary active" data-wat='foo'>
<input type="checkbox"> Item 1
</label>
<label class="btn btn-primary" data-wat='bar'>
<input type="checkbox"> Item 2
</label>
<label class="btn btn-primary" data-wat='something'>
<input type="checkbox"> item 3
</label>
<label class="btn btn-primary" data-wat='orElse'>
<input type="checkbox"> item 4
</label>
</div>
The Button row acts like it should do.
Then I watch for a click event on the .arrUpdate div for change. I've got multiple button groups which all have the .arrUpdate class. That's the reason for the second class: .arrActiviteit
$('.arrUpdate').click(function(e){
val = ''; // for holding the temporary values
$('.arrActiviteit label').each(function(key, value){
if(value.className.indexOf('active') >=0){
val += value.dataset.wat
}
})
// just for debug reasons.
$('#hierHier').html(val);
})
But it appears that the 'active' class gets added after the click event is fired. So the value in #hierHier is always behind one click, so to say.
How can I resolve this?
Or is there a better way to retrieve all the active buttons in this checkbox-array?
SOLVED
update: better solution Twitter Bootstrap onclick event on buttons-radio
http://jsfiddle.net/hA423/7/
I solved it using a timeout to make your function run after bootstrap events...
There must be some other ways to do it...
$('.btn').on('click',function(e){
setTimeout(count);
})

Twitter bootstrap managing multiple radio buttons through Javascript in rails

I am using twitter bootstrap in my rails app, and I am constructing a form with multiple radio button inputs. In order to manage the form data, I have created a hidden field whose value is updated via Javascript.
Sample code below for any given input:
<div class="btn-group" data-toggle="buttons-radio">
<button type="button" class="btn" id="ornamental_only_yes" name="ornamental_only" value="yes">Yes</button>
<button type="button" class="btn" id="ornamental_only_no" name="ornamental_only" value="no">No</button>
</div>
<input type="hidden" id="ornamental_only" name="ornamental_only" value="">
Here is the Javascript to manage this event:
<script>
var btns = ['ornamental_only_yes', 'ornamental_only_no'];
var input = document.getElementById('ornamental_only');
for(var i = 0; i < btns.length; i++) {
document.getElementById(btns[i]).addEventListener('click', function() {
input.value = this.value;
});
}
</script>
My question: Is there a way to abstract the Javascript code in such a way as to apply to multiple radio button inputs simultaneously? (For instance, if I had 3 repetitions of the code block above with different id's)
Let's assume this is your HTML with multiple sets of buttons:
<div class="btn-group" id="btn_group_1" data-toggle="buttons-radio">
<button type="button" class="btn" id="ornamental_only_yes" name="ornamental_only" value="yes">Yes</button>
<button type="button" class="btn" id="ornamental_only_no" name="ornamental_only" value="no">No</button>
</div>
<input type="hidden" id="hidden_1" name="ornamental_only" value="">
<div class="btn-group" id="btn_group_2" data-toggle="buttons-radio">
<button type="button" class="btn" id="awesome_only_yes" name="awesome_only" value="yes">Yes</button>
<button type="button" class="btn" id="awesome_only_no" name="awesome_only" value="no">No</button>
</div>
<input type="hidden" id="hidden_2" name="awesome_only" value="">
To dynamically listen for clicks on all button groups, you could do something like this (untested jQuery):
$('.btn-group .btn').on('click', function() {
var parentID = $(this).parent().attr('id');
$('#hidden_' + parentID.substr(parentID.length - 1)).val($(this).val());
});
This just targets the hidden input fields based on the number at the end of the id.
Try using this:
for(var i = 0; i <= btns.length; i++) {
Use jQuery.
var buttonObjs = $(".btn-group").find("button");
buttonObjs.click(function(){
$("#ornamental_only").val(this.value);
});
To apply this code to multiple blocks, all you need to do is assign a specific class to the btn-group element, something like,
<div class="btn-group js_radio_toggle">
In the js code just use,
var buttonObjs = $(".btn-group.js_radio_toggle").find("button");
now this code can be reused anywhere.
also in your js code. you can do this,
document.getElementsByClassName("js_radio_toggle").
But I would recommend you to use jQuery.

Categories