Reputation: 9923
I have seen a few answers on here and the web but as I need to ask something else I have made this question. + I cant seem to get anything to work.
So what I'm after is Yes
and No
options, these will be buttons and when pressed they will stay active as they will make a div
appear on the page depending on there value.
E.G:
Yes = <div id="won">You won</div>
No = <div id="lose">You lost</div>
These divs will appear under the buttons. My question is how can I get the value from a div? I tried to use radio buttons inside to get this working but I cant seem to do it.
What I have so far.
<div class="buttonHolder">
<div class="option">Yes
<input id="yes" type="radio" />
</div>
<div class="option">No
<input id="no" type="radio" />
</div>
</div>
div {
outline: 1px solid;
}
.buttonHolder {
width: 400px;
height: 150px;
}
.buttonHolder1 {
background: red;
}
.option {
width: 50%;
height: 100%;
float: left;
background: #eee;
cursor:pointer;
}
.optiontest {
background: #fff;
}
$('.option').click(function () {
var $this = $(this);
var input = $this.find('input');
$('.optiontest').toggleClass('optiontest');
$(input).prop('checked', true);
$(this).toggleClass('optiontest');
});
So the buttons will look like that and change background when pressed as well as bringing up another question etc... There will be multiply questions and answers on the same page.
Forgot to add that I would like the radio button not visible, so it looks like the div
is selected and there is no radio button. Apologises for not adding that when writing the question.
Upvotes: 1
Views: 140
Reputation: 9738
May be this will help :-
<div class="buttonHolder">
<div class="option1">Yes
</div>
<div class="option2">No
</div>
Upvotes: 0
Reputation: 578
What about something like this?
The jQuery is pretty simple:
$('input[name="options"]').click(function () {
$('.optiontest').removeClass('optiontest')
$(this).closest('.option').toggleClass('optiontest')
});
And I modified your HTML to give the radio buttons values (you had it set as ID's) and the same name, which gives them the correct radio button behaviour.
<div class="buttonHolder">
<div class="option">Yes
<input name="options" value="yes" type="radio" />
</div>
<div class="option">No
<input name="options" value="no" type="radio" />
</div>
</div>
Upvotes: 0
Reputation: 5982
you can include the data attribute in the DIV
look at your jsfiddle, i have made some modification in HTMl and Jquery: http://jsfiddle.net/bNNA6/1/
$('.option').click(function () {
var $this = $(this);
var input = $this.find('input');
$('.optiontest').toggleClass('optiontest');
$(input).prop('checked', true);
$(this).toggleClass('optiontest');
var dataValue = $this.data("optionvalue"); // using data attribute to put the value
alert(dataValue);
});
Upvotes: 1