Reputation: 225
I have some trouble retrieving the value assigned to my DIVs. The DIVs contains answers to a survey. (I can't use other inputs such as select, radio button)
Below is the form:
<form id='Form01' action=''>
<div class="box" id='input01' onclick="submit_answer()" value='1'>YES</div>
<div class="box" id='input02' onclick="submit_answer()" value='2'>NO</
</form>
Below is the function to retrieve the answers:
function submit_answers(e) {
OPTION1: var answer = $(#input01).attr('value'); // RETURNS "1"
OPTION2: var answer= $(this).attr('value'); // **RETURNS "Undefined"**
console.log(answer) ;
$.post('input_answers.php',{value:answer});
}
I'd like to insert '1' if the respondent clicks on "YES", '2' for "NO" but
var value01 = $(this).attr('value');
returns 'UNDEFINED.
Thank you for your help.
Upvotes: 1
Views: 383
Reputation: 1027
There are 2 things wrong with your code:
To fix your JS correctly (and keep your use of jQuery) try the following:
function submit_answers(e) {
var value01 = $(this).attr('value');
$.post('input_answers.php',{value:value01});
}
Other issues I note with your code:
EDIT: after updated question As the JavaScript and HTML have changed substantially since my initial answer. Further issues are:
Issues fixed in the (substantial) edit:
Upvotes: 1
Reputation: 1413
try like this
$("#input01,#input02").click(function(){
var answer= $(this).attr('value');
console.log(answer) ;
$.post('input_answers.php',{value:answer});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='Form01' action=''>
<div class="box" id='input01' value='1'>YES</div>
<div class="box" id='input02' value='2'>NO</div>
</form>
Upvotes: 1