mactron
mactron

Reputation: 71

Radio Button Value with Javascript

I am fetching data from MySQL using Javascript. I looked and tried everything (from id, from class, from name) to get the selected value from radio button, but without success.

I tried all these options but nothing works..

$('.action').val(data.action); 

$('#action').val(data.action); 

$("input[name='action']:checked").val(data.action); 

Here is the piece of my HTML code..

 <form method="post" id="insert_form">
  <div class="form-group">

    <div class="form-group">
      <div class="form-check form-check-inline">
        <label for="action">ACTION: &nbsp; &nbsp;</label>
          <label class="form-check-label">
            <input type="radio" name="action" value="buy" class="form-check-input action"> Buy
          </label>

          <label class="form-check-label">
            <input type="radio" name="action" value="sell" class="form-check-input action" > Sell
          </label>
        </div>
          <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-primary" /> 
      </div>
  </form>
  </div>

... and here is the piece of my Javascript code..

  $(document).on('click', '.edit_data', function(){  
       var signal_id = $(this).attr("id");  
       $.ajax({  
            url:"fetch.php",  
            method:"POST",  
            data:{signal_id:signal_id},  
            dataType:"json",  
            success:function(data){
                $('#pair').val(data.pair);  
                $('#entry').val(data.entry);
                //$('.action').val(data.action); 
                $("input[name='action']:checked").val(data.action); 
                $('#direction').val(data.direction); 
                $('#t_p').val(data.t_p);
                $('#s_l').val(data.s_l);
                $('#add_analysis').val(data.add_analysis);  
                $('#notes').val(data.notes);   
                $('#signal_id').val(data.id);  
                $('#insert').val("Update"); 
                $('#add_data_Modal').modal('show');  

            }  
       });  
  });

Upvotes: 1

Views: 353

Answers (1)

Eddie
Eddie

Reputation: 26844

Based on what I understand, you are trying to set the values on the radio buttons based on the result/response from ajax/MySQL.

This is how $('input:radio').prop('checked',true); to set if radio button is selected or not.

$(document).ready(function(){
	//temporary code
	var action = 1;
				
	if ( action == 1 ) $('input:radio[value=buy]').prop('checked',true);
	else $('input:radio[value=sell]').prop('checked',true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="radio" name="action" value="buy" class="form-check-input action"> Buy
<input type="radio" name="action" value="sell" class="form-check-input action"> Sell

Upvotes: 1

Related Questions