Checkbox doesn't store the value - javascript

I am trying to create a dynamic Question List along with its dynamic options. With each option I maintain a flag using checkbox. If the checkbox is clicked the AnalysisFlag value should be true and if not then it should be false. However using the below mentioned method, I am always getting the false value whether I clicked the checkbox or not.
Can someone please take a look and suggest me how I can maintain the AnalysisFlag value along with its equivalent option?
function GetDynamicTextBox(value) {
var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("class", "form-control").attr("placeholder","Your Answer");
textBox.val(value);
debugger;
**var allVals = [];
$('[name="DynamicAnalysisFlag"]:checked').each(function () {
allVals.push($(this).val());
});**
return textBox, allVals;
}
var j = 66;
var x = 2;
var option = 'option' + x;
function AddTextBox() {
for (var i = j; i <= j; i++) {
$('#TextBoxContainer' + x).after("<br id='Removebr" + (x + 1) + "'><div class='input-group' id='TextBoxContainer" + (x + 1) + "'><div class= 'input-group-prepend'><div class='input-group-text'> " + String.fromCharCode(i) + " **<input type='checkbox' id='DynamicAnalysisFlag' value= 'true' name='DynamicAnalysisFlag' class='checklistitem''></div>**</div><input autocomplete='off' class='form-control test-option test-option" + x + " text-box single-line' data-val='true' data-val-required='Answer is required' id=" + option + " name='DynamicTextBox' placeholder='Your Answer' type='text' value=''><span class='field-validation-valid text-danger' data-valmsg-for='AnalysisFlag' data-valmsg-replace='true'></span></div>");
}
j++;
x++;
}
function RemoveTextBox() {
if (x != 2) {
$('#TextBoxContainer' + x).remove();
$('#Removebr' + x).remove();
--x;
--j;
}
}
$('#btnNext').on('click', function() {
var radioValue1 = $("input[name='AnalysisFlag']:checked").val();
var txtVal = $('.test-option' + radioValue1).val();
$('#hiddenRadioValue').val(txtVal);
});
$(function() {
var values = eval('#Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function() {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});
<div id="radio" class="col-xs-12">
<br id="Removebr2">
<div class="input-group" id="TextBoxContainer2">
<div class="input-group-prepend">
<div class="input-group-text">
A
<input type="checkbox" id="radio1" value="1" name="AnalysisFlag" onselect="alert('clicke')">
</div>
</div>
<input autocomplete="off" class="form-control test-option test-option1 text-box single-line" data-val="true" data-val-required="Option is required" id="opt1" name="opt1" placeholder="Your Answer" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="opt1" data-valmsg-replace="true"></span>
<input data-val="true" data-val-required="The AnalysisFlag field is required." id="hiddenRadioValue" name="AnalysisFlag" type="hidden" value="">
<br>
</div>
</div>
<div class="card-footer">
<input type="submit" id="btnNext" value="Next ยป" class="btn btn-primary vigor-btn">
</div>
<button type="button" id="btnRemove" class="btn btn-primary vigor-btn" onclick="RemoveTextBox()">Remove Options</button>
<button type="button" id="btnAdd" class="btn btn-primary vigor-btn" onclick="AddTextBox()">Add Options</button>
I have edited the GetDynamicTextBox() function in which I am getting the DynamicAnalysisFlag value which I add at the time of adding another textbox in AddTextBox() function. But now the issue is, if I tick the checkbox I am getting the true value but if I don't tick the checkbox I am getting nothing. So, what changes should I do in this code so if I check the code, I get true and if not then I get false.

Related

How to display the total number of quantity in the input box

I have a quantity field. The user can add multiple quantity fields on click on Add button.
My issue is, I have to display the total number of quantity in the input box. for example I added 10 quantity in the quantity box and the total is 10 in the total box.
The user can increase and decrease the quantity on click on plus and minus button as well as direct enter then quantity in the quantity box and total will display in the total box.
The user can add multiple quantities field same as on remove. I click on to remove the quantity should be removed from the total quantity field.
You can also check my code here as well https://jsfiddle.net/pu6qy4zr/70/
function increaseValue(n) {
var value = parseInt(document.getElementById('number' + n).value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number' + n).value = value;
}
function decreaseValue(n) {
var value = parseInt(document.getElementById('number' + n).value, 10);
value = isNaN(value) ? 0 : value;
value < 1 ? value = 1 : '';
value--;
document.getElementById('number' + n).value = value;
}
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".add_row"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$("input[id^=medication_name]").focus();
$(wrapper).append('<div class="custom_fields"><div class="col-md-6"><div class="row"><div class="col-md-6"><div class="form_group"><div class="plus_minus"><span class="value_button decrease" onclick="decreaseValue(' + x + ')" value="Decrease Value"> - </span><input type="number" id="number' + x + '" class="qty_number form_control" name="qty_number[]" class="form_control" value="0" /><span class="value_button increase" onclick="increaseValue(' + x + ')" value="Increase Value"> + </span></div></div></div><div class="col-md-6"><div class="form_group"> <div class="btn_row remove_field"> <span> - </span> Remove </div></div></div></div></div></div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).closest('.custom_fields').remove();
x--;
})
});
<div class="add_row">
<div class="plus_minus">
<span class="value_button decrease" onclick="decreaseValue(1)" value="Decrease Value">-</span>
<input type="number" id="number1" class="qty_number form_control" name="qty_number[]" value="0" class="form_control" />
<span class="value_button increase" onclick="increaseValue(1)" value="Increase Value">+</span>
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
</div>
<input type="text" class="form_control" name="total_qty" id="total_qty" value="" placeholder="Total number of quantity" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can simplify all this.
run sum() on each change including the remove and direct input/paste.
only have one event handler for the plus/minus
remove the inline handlers
PS: I found a bug: value < 1 ? value = 1 : ''; would force a value of 1
PPS: I suggest you use .clone for the div instead of inserting it. Makes it much easier to update the HTML. Since I delegate and use relative addressing, you do not need to change the IDs of the fields
function sum() {
var total = 0;
$(".qty_number").each(function() { // or use .map.get()
total += this.value?parseInt(this.value):0;
})
$("#total_qty").val(total);
}
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var $wrapper = $(".add_row"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var x = 1; //initlal text box count
$(add_button).on("click",function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$("input[id^=medication_name]").focus();
$wrapper.append('<div class="custom_fields"><div class="col-md-6"><div class="row"><div class="col-md-6"><div class="form_group"><div class="plus_minus"><span class="value_button decrease" value="Decrease Value"> - </span><input type="number" id="number' + x + '" class="qty_number form_control" name="qty_number[]" class="form_control" value="0" /><span class="value_button increase" value="Increase Value"> + </span></div></div></div><div class="col-md-6"><div class="form_group"> <div class="btn_row remove_field"> <span> - </span> Remove </div></div></div></div></div></div></div>');
}
});
$wrapper.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).closest('.custom_fields').remove();
x--;
sum(); // remove also updates the total
})
$wrapper.on("click",".value_button",function() {
var $input = $(this).closest(".plus_minus").find(".qty_number");
var value = parseInt($input.val(), 10);
value = isNaN(value) ? 0 : value;
value+=$(this).is(".decrease")?-1:1; // decrease on increase dependent on class
if (value < 0) value=0;
$input.val(value);
sum(); // sum each time
});
$wrapper.on("input",".qty_number",sum); // any input or paste
});
<div class="add_row">
<div class="plus_minus">
<span class="value_button decrease" value="Decrease Value">-</span>
<input type="number" id="number1" class="qty_number form_control" name="qty_number[]" value="0" class="form_control" />
<span class="value_button increase" value="Increase Value">+</span>
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
</div>
<input type="text" class="form_control" name="total_qty" id="total_qty" value="" placeholder="Total number of quantity" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Pass the values from View to Controller for Dynamically populated forms

I have a form in which the TextBox is dynamically populated. The user has the flexibility to add and remove TextBox which is done using JQuery.
I would need to pass the value of TextBox to my Controller on Submit.
This is my View.
#using (Html.BeginForm("Controller", "Admin", FormMethod.Post, new { required = "required" }))
{
<h4>Add new Q&A</h4>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type="text" name="Question" id="Question" required placeholder="Question 1" class="form-control" /><br />
</div>
</div>
<input type="button" name="Add" id="Add" value="Add" class="btn btn-success" />
<input type="button" name="Remove" id="Remove" value="Remove" class="btn btn-danger" /> <br /><br />
<textarea rows="5" name="Answer" id="Answer" placeholder="Answer" required class="form-control"></textarea><br />
#Html.DropDownList("Intent", ViewData["Intent"] as List<SelectListItem>, "Select Intent", new { #class = "form-control", required = "required" })
<br /><input type="text" name="PrimaryEntity" id="PrimaryEntity" placeholder="Primary keyword" required class="form-control" /><br />
<input type="text" name="SecondaryEntity" id="SecondaryEntity" placeholder="Secondary keyword (optional)" class="form-control" /><br />
<input type="submit" name="Submit" id="Submit" class="btn btn-success" />
}
This is how my JS looks
$(document).ready(function () {
var counter = 2;
$("#Add").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter +
'" id="Question' + counter + '" value="" class="form-control" required placeholder="Question ' + counter +
'"> <br />');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#Remove").click(function () {
if (counter == 2) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
Sorry if I sound lame. Just getting started with MVC!
You can create a simple model having property Questions of List<string> type and other required properties.
Then from jQuery you can add multiple TextBoxes using a simple logic:
<input type="text" name="Model.Questions[" + index + "]" id="Model_Questions_" + index />
Render using:
#for (int i = 0; i < Model.Questions.Count; i++)
{
#Html.TextBoxFor(x => Model.Questions[i], { .... })
}
When you post your form, all values in questions textboxes will be posted to your model's Questions list.
Note: I have not written above code in VS, so there may be some errors which you can fix yourself.

Dynamic add multi fields in javascript

I am beginner in javascript. I need to dynamic add multifields in existing form that have same id.
first fields has this name :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
And when clicking "Add another text input" I want a new fields with
<input type="text" name="myInputs[1][address]">
<input type="text" name="myInputs[1][whitelist]">
and clicking again on "Add another text input"
<input type="text" name="myInputs[2][address]">
<input type="text" name="myInputs[2][whitelist]">
When submit post only the first fields are posted :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
Here the code :
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs["+ (counter + 1) +"][address]'><input type='text' name='myInputs["+ (counter + 1) +"][whitelist]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
<div id="dynamicInput">
Entry 1<br>
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">

Dynamic textboxes are not removing

I am adding textboxes through jquery and for one text box it is removing perfeclty but when I add two textboxes then it does now remove both.
this is jquery
<script>
$(document).ready(function($){
$('.product-form .add-product').click(function(){
var n = $('.text-product').length + 1;
var product_html = $('<p class="text-product"><label for="product' + n + '">Name <span class="product-number">' + n + '</span></label> <input required type="text" name="productnames[]" value="" id="product' + n + '" /> <label for="productprice' + n + '">Price <span class="product-number">' + n + '</span></label> <input required type="text" name="productprices[]" value="" id="productprice' + n + '" />Remove</p>');
product_html.hide();
$('.product-form p.text-product:last').after(product_html);
product_html.fadeIn('slow');
return false;
});
$('.product-form').on('click', '.remove-category', function(){
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.product-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
and this is my html
<div>
<form>
<div class="product-form">
<p class="text-product">
<label for="product1">Name <span class="product-number">1</span></label>
<input required type="text" name="productnames[]" value="" id="product1" />
<label for="product1">Price <span class="product-number">1</span></label>
<input required type="text" name="productprices[]" value="" id="product1" />
<div>
<a class="add-product" href="#">Add More</a>
</div>
</p>
</div>
<div>
<input type="submit" name="submitDetails" value="Finish"/>
</div>
</form>
</div>
If only one textbox for instance productnames is added then it removal function works but when I add botch productnames and productprices textbox removal function does not remove both
Your code should read $('.product-form').on('click', '.remove-product', function() rather than 'click', '.remove-category'. Also, don't place the Add More div element inside the paragraph element. The numbering also breaks a bit, but you can figure that out.

how to require click on a button

I have a form with this inputs and buttons :
<input type="number" id="inputs" name="inputs" min="3" max="48" pattern=".{1,2}" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id ="button2" value="next">
And I'm using this javascript code to append number of the "inputs" that the user have insert in this button :
$(function()
{
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=1;i<=c;i++)
{
$("#mydiv").append('<input type="text" id="name'+i+'" name="name'+i+'" placeholder="name'+i+'">');
$("#mydiv").append('<input type="number" id="rating'+i+'" name="rating'+i+'" min="1" max="10" placeholder="rating'+i+'"><br/>');
}
});
$("#button2").click(function()
{
if(c===0)
alert('must click on "continue" button');
});
});
});
I'm trying to require the user to enter a value in "inputs" (input type) and click on the "continue" (button1) button. With that way it's not working (must enter a value in the "inputs" but can click on "button2" without clicking on "button1"). How do I require the user to click also on the "button1" (continue) ?
Thanks.
$(function() {
var c = 0;
$("#button1").click(function() {
if( !$('#inputs')[0].checkValidity() ) {
alert( $('#inputs')[0].title );
return false;
}
c = +$("#inputs").val();
$("#mydiv").html("");
for (i = 1; i <= c; i++) {
$("#mydiv").append('<input type="text" id="name' + i + '" name="name' + i + '" placeholder="name' + i + '">');
$("#mydiv").append('<input type="number" id="rating' + i + '" name="rating' + i + '" min="1" max="10" placeholder="rating' + i + '"><br/>');
}
$('#button2').prop('disabled',false);
});
$("#button2").click(function() {
if (c === 0) {
alert('must click on "continue" button');
} else {
alert('Now let us move ahead');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="inputs" name="inputs" min="3" max="48" pattern=".{1,2}" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id="button2" value="next" disabled>
$(function() {
var c = 0;
$("#button1").click(function() {
if ($("#inputs").val().length > 0 && $("#inputs").val().length < 3 && $("#inputs").val() != 0) {
c = $("#inputs").val();
$("#mydiv").html("");
for (i = 1; i <= c; i++) {
$("#mydiv").append('<input type="text" id="name' + i + '" name="name' + i + '" placeholder="name' + i + '">');
$("#mydiv").append('<input type="number" id="rating' + i + '" name="rating' + i + '" min="1" max="10" placeholder="rating' + i + '"><br/>');
}
$("#button2").prop('disabled', false);
} else {
$("#button2").prop('disabled', true);
alert("Value is empty / to low / to high. Insert a value between 1 and 99");
}
});
$("#button2").click(function() {
if(c > 0 && $("#inputs").val() > 0){
alert('piu piu');
}
else{
alert('sorry, check your inputs');
$("#button2").prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="inputs" name="inputs" min="3" max="48" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id="button2" value="next" disabled>
You can disable button2 and make it enable on click of button1, see below code
<input type="number" id="inputs" name="inputs" min="3" max="48" pattern=".{1,2}" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id ="button2" value="next" disabled>
jQuery
$(function()
{
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val().trim();
$("#mydiv").html("");
for(i=1;i<=c;i++)
{
$("#mydiv").append('<input type="text" id="name'+i+'" name="name'+i+'" placeholder="name'+i+'">');
$("#mydiv").append('<input type="number" id="rating'+i+'" name="rating'+i+'" min="1" max="10" placeholder="rating'+i+'"><br/>');
}
//enable your button 2 if input has value
if(c!='')
$("#button2").removeProp('disabled');
});
$("#button2").click(function()
{
//submit your form here
});
});
Change this line:
c = $("#inputs").val();
to
if($("#inputs").val() != "")
c = $("#inputs").val();

Categories

Resources