Nadal
Nadal

Reputation: 105

How to merge 2 different jquery event functions?

I need to pass values from a text input and radio input fields, to a hidden text input. All works fine when entry is done individually but each replaces the other when triggered. I need to append the radio onto the text input.

$(function() {
  $("#text").keyup(function() {
    var text = ($("#text").val() != "" ? $("#text").val()+"," : "");
    $("#hidden").val(text);
  });
  $("input[name=radio]").click(function() {
    var radio = $("input[name=radio]:checked").val();
    $("#hidden").val(radio);
  });
});

What I need as the output

$("#hidden").val(text + radio);

What I tried

$(function() {
  $("#text").keyup(function() {
    var text = ($("#text").val() != "" ? $("#text").val()+"," : "");
  });
  $("input[name=radio]").click(function() {
    var radio = $("input[name=radio]:checked").val();
  });

  $("#hidden").val(text + radio);
});

But no values are returned.

How can I concatenate the output of keyup() and click() events?

Upvotes: 0

Views: 70

Answers (2)

mplungjan
mplungjan

Reputation: 177950

Try this

function getText() {
  var text = [], val = $.trim($("#text").val()), $rad = $("input[name=radio]:checked");
  if (val) text.push(val);
  if ($rad.length >= 1) text.push($rad.val());
  $("#hidden").val(text.join(","));
}
$(function() {
  $("#text").on("input",getText);
  $("input[name=radio]").on("change",getText);
});

Upvotes: 1

Ganesh Putta
Ganesh Putta

Reputation: 2681

Try this, it works fine

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var radioValue="";
var text="";
$(function() {
  $("#text").keyup(function() {  
   	text = ($("#text").val() != "" ? $("#text").val()+"," : "");
    if($("input[name='gender']:checked").val()!=undefined){
   	 checkedValue = $("input[name='gender']:checked").val();
    }
    else{
   	checkedValue = ""
    }
    $("#hidden").text(text + "--" + checkedValue);
  });
  $("input[name='gender']").click(function() {
  	textValue = $("#text").val();
   	radioValue = $("input[name='gender']:checked").val();
    $("#hidden").text(textValue + "--" +radioValue);
  });
});
</script>
</head>
<body>
<input type="text" id="text"/><br/><br/>
 <label><input type="radio" name="gender" value="male">Male</label> 
        <label><input type="radio" name="gender" value="female">Female</label><br/>
<label id="hidden" style="color:red;font-weight:bold;"></label>
</body>
</html>

Upvotes: 0

Related Questions