Reputation: 105
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);
});
});
$("#hidden").val(text + radio);
$(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
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
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