Function that generates multiple dynamic ID's with a defined pattern - javascript

I am trying to make a function that generates multiple dynamic ID's with a defined pattern, how do I do that?
followup: Vue.js: How to generare multiple dynamic ID's with a defined pattern
Details:
I am creating a dynamic school-test application. When the button "Add question" is clicked, a
div with 4 input fields and 4 radio buttons are generated. Each input and radio button needs to have an ID.
So far, the function generates a value, that I hope can be used as an ID. Every radio button has a
name, that makes it possible to only choose one option in the group it belongs to. With every button
click on the "Add Question" button (which is a radio button), this particular "name" is used to count button clicks. With the help of the counter, the dynamic ID for the "question" input field and "options" input fields
(that is connected to the radio buttons) is generated in this pattern:
Example
Testtitle-Question-Option
JavaScriptQ1 (Question)
JavaScriptQ1O1 (Option)
JavaScriptQ1O2
JavaScriptQ1O3
JavaScriptQ1O4
Since there is a div that is generated when the test is launched, and the ID is only generated by button clicks one
div won't get it's ID's. It seems that there is only one question in the ID's in the example above when it's in fact two!
I am currently not using saveTest(), which will be used to save the test into a mySQL database, but it may be used to solve this!
1. I want that one extra "group of ID's" is generated, so each input field gets an ID, but how do I do that?
2. When this matter is solved, how do I generate unique ID's for the radio buttons?
3. How do I then do to use the generated values as ID's. How do I "attach" them to their input fields and radio buttons?
4 Is there any other, better ways to solve this? The ID's has to follow a certain pattern since they will be saved in
a database and then be used to correct the tests.
I know that it's a rather complex issue, but I have tried to explain as good as possible.
I advise that you look at the jsfiddle instead! Click on Add Question and you will see how it works.
var name=1;
$("body").on('click', '#radioAddQuestion', function () {
var singleQuestionModule = "singleQuestionModule";
var question = $(".module:first").clone()
.find("input:text").val("").end();
var question_label = $(".question-label:first").clone();
$(question).find(':radio').prop('checked', false);
$(question_label).insertBefore(".options-label:last");
$(question).insertBefore(".options-label");
$(question).find(':radio').attr('name', "n" + name);
// Here is where the ID value is currently generated:
name++;
let questionId = theTitle + "Q" + name;
console.log(questionId);
for (a = 1; a <= 4; a++) {
let optionId = theTitle + "Q" + name + "O" + a;
console.log(optionId);
}
console.log(name)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="singleQuestionModule">
<form class="form-group">
<div class="input-group input-group">
<label id="wQuestionLabel" class="form-control-label" style="width: 540px;" for="wQuestion">Question:</label>
</div>
<!-- The Question Inputfield that needs ID-->
<div class="input-group input-group">
<input type="text" class="form-control" aria-label="" id="wQuestion" style="width: 540px;">
</div>
<div class="input-group input-group">
<label id="questionOptions" class="form-control-label" style="width: 540px;" for="wQuestion">Enter avaible options:</label>
</div>
<!-- The radio buttons and option input fields that need ID's-->
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name= "q" id="option1" aria-label="">
</span>
<input type="text" class="form-control" aria-label="" style="width: 540px;">
</div>
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="q" id="option4" aria-label="">
</span>
<input type="text" class="form-control" aria-label="" style="width: 540px;">
</div>
<!-- The Add and Save Test Buttons-->
<span class="options-label"></span>
<br>
<div class="form-group row">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success" id="radioAddQuestion">
<input type="radio" #click="counter += 1" name="options" autocomplete="off">Add Question</label>
<label class="btn btn-success">
<input type="radio" name="options" id="radioSaveTest" value="saveTest()" autocomplete="off">Save Test </label>
</div>
</div>

I changed the script. just have look on that. It will generate dynamic ID for all controls that you have been used.
var name=1;
var theTitle="online";
$("body").on('click', '#radioAddQuestion', function () {
name++;
$(".dynamicform").append(createQuestion(name));
});
$(".dynamicform").append(createQuestion(name));
function createQuestion(name){
var dynamic=`<span class="module">
<legend class="col-form-legend col-sm-10"></legend>
<div class="input-group input-group">
<label id="wQuestionLabel" class="form-control-label" style="width: 540px;" for="wQuestion">Question:</label>
</div>
<div class="form-group row">
<div class="input-group input-group">
<!-- The Question Inputfield that needs ID-->
<input type="text" class="form-control" aria-label="" id="${theTitle + "Q" + name}" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<label id="questionOptions" class="form-control-label" style="width: 540px;"
for="wQuestion">Enter
avaible options:</label>
</div>
</div>
<!-- The radiobuttons and option inputfields that needs ID's-->
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "1"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "1"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "2"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "2"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "3"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "3"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" name="${theTitle +"rg"+name}" id="${theTitle + "Q" + name + "O" + "4"}" aria-label="">
</span>
<input type="text" id="${theTitle + "Q" + name + "input" + "4"}" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
</span>
`;
return dynamic;
}
#singleQuestionModule {
margin-left: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="singleQuestionModule">
<form class="form-group">
<div class="d-flex justify-content-center">
<fieldset class=" form-group row">
<div class="dynamicform">
<!--Dynamic form comes here-->
</div>
<span class="options-label"></span>
<br>
<div class="form-group row">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success" id="radioAddQuestion">
<input type="radio" #click="counter += 1" name="options" autocomplete="off">Add Question</label>
<label class="btn btn-success">
<input type="radio" name="options" id="radioSaveTest" value="saveTest()" autocomplete="off">Save
Test </label>
</div>
</div>
</fieldset>
</div>
</form>
</div>
Jsfiddle : https://jsfiddle.net/d9tfk1u6/

Why don't you just put a first id on the elements that are already there? If you want to use the first id that comes out of the id generation function, either change the id generation function so it skips that, or use an onload to add it.
This seems like the obvious solution to the problem, so maybe I've misunderstood it.

Related

jQuery Cloning and incrementing input, textarea, that has name, id and for

I'm still very new to jQuery, and would need help to how to increment 3 elements in this code.
name, id & for.
The name consist of products[0]category, id consist of checkbox[0], for consist of checkbox[0] which is for labels on the checkbox that id use.
I've tried searching for examples. But all them haven't found any good results that i could learn from unfortunately. So in the codes below, they're not there to increase increment as i have totally no idea what else i can do to increase increment numbering.
$(document).ready(function() {
let $append = $('#append');
// append location's data listing
$append.on('change', '.location', function(){
var value = $(this).val();
$('.location_id').val($('#locations [value="'+value+'"]').data('locationid'));
$('.loc_desc').val($('#locations [value="'+value+'"]').data('locdesc'));
});
// enable checkbox for serialnumbers
$append.on('change','.enable-serial', function(){
let $item = $(this).closest('.product-item');
let $checkbox = $item.find('.enable');
$checkbox.prop('disabled', !this.checked);
});
// ctrl for key in checkbox
$append.on('click', '.keyin-ctrl', function() {
let $container = $(this).closest('.product-item');
let $serial = $container.find('.serial');
$container.find('.display').val(function(i, v) {
return v + $serial.val() + ';\n';
});
$serial.val('').focus();
});
// ctrl for del textarea
$append.on('click', '.undo-ctrl', function() {
let $container = $(this).closest('.product-item');
$container.find('.display').val('');
});
// clone product, increment products[x]var
$('#add_product').on('click', function() {
var itemNo = $('.product-item').length + 1;
var index = $('.product-item').length;
var regex = /^(.+?)(\d+)$/i;
let $product = $append.find('.product-item.template')
.clone()
.show()
.removeClass('template')
.insertAfter('.product-item:last');;
$product.find('span').text('#' + itemNo);
$product.find(':checkbox').prop('checked', false);
$product.find('.enable').prop('disabled', true);
$product.find('input, textarea').val('');
$('#append').append($product);
});
// delete product, but remain original template intact
$('#delete_product').on('click', function(){
var itemNo = $('.product-item').length + 1;
let $product = $append.find('.product-item:last:not(".template")');
$product.remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="shadow border">
<h4>{{ __('Product Details') }}</h4>
<hr>
<form method="post" action="">
<!-- Multiple Product addition -->
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Product Setting') }}</label><br/>
<div class="col-sm-5">
<button type="button" id="add_product" class="btn btn-dark">{{ __('Add Product') }} <i class="fas fa-plus-square"></i></button>
<button type="button" id="delete_product" class="btn btn-dark ml-3">{{ __('Delete Last Product') }} <i class="fas fa-minus-square"></i></button>
</div>
</div>
<hr>
<!-- Frist Group -->
<div class="product" id="append">
<!-- Product Details -->
<div class="product-item template">
<span>#1</span>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Category') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]category" type="text" placeholder="eg. 333" maxlength="3"required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Code') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]code" type="text" placeholder="eg. 22" maxlength="2" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Partnumber') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]partnumber" type="text" placeholder="eg. NGH92838" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Brand') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]brand" type="text" placeholder="eg. Rototype" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Quantities') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]qty" type="number" placeholder="eg. 1" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __("Location") }}</label>
<div class="col-sm-2">
<input class="form-control location" type="text" name="products[0]loc_name" list="locations" value="">
<input type="hidden" class="location_id" name="products[0]location_id" value="">
<input type="hidden" class="loc_desc" name="products[0]loc_desc" value="">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __("Description") }}</label>
<div class="col-sm-8">
<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Seial Number(s)') }}</label>
<div class="col-sm-5">
<input class="form-control enable serial" maxlength="25" placeholder="Key in Serial Number and hit button 'Key In'" disabled>
</div>
<div class="col-sm-5">
<button class="btn btn-dark enable keyin-ctrl" type="button" disabled>{{ __('Key In') }}</button>
<button class="btn btn-dark enable undo-ctrl" type="button" disabled>{{ __('Del') }}</button>
<input class="form-check-input ml-4 mt-2 pointer enable-serial" id="checkbox[0]" type="checkbox">
<label class="form-check-label ml-5 pointer" for="checkbox[0]">{{ __('tick to enable serialnumber')}}</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-5">
<textarea class="form-control display" name="products[0]serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>
</div>
</div>
<hr>
</div>
<!-- append start -->
</div>
<div class="form-group row">
<div class="col-sm-12 ">
#csrf
<button type="submit" class="btn btn-dark float-right ml-4">Next <i class="fas fa-caret-right"></i></button>
<!--<button type="button" class="btn btn-secondary float-right" onclick="history.back()">Previous</button>-->
</div>
</div>
<datalist id="locations">
#foreach($locations as $location)
<option value="{{ $location->loc_name}}" data-locationid="{{ $location->location_id }}" data-locdesc="{{ $location->loc_desc }}"></option>
#endforeach
</datalist>
</form>
</div>
</main>
So how do I actually achieve this to add increment to the NAME, ID and FOR my clones?
From the original template of products[0]variable to products[1]variable, checkbox[0] to checkbox[1]
If you want to increment either an ID, class, etc. you can't use .clone(), like the documentation warns:
Using .clone() has the side-effect of producing elements with
duplicate id attributes, which are supposed to be unique. Where
possible, it is recommended to avoid cloning elements with this
attribute or using class attributes as identifiers instead.
You'll have to do it "manually", following a very simple example below:
$( "#addrow" ).click(function() {
var count = $("#product").children().length;
$("#product").append("<input id='field[" + count + "]' type='text'>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="product">
</div>
<input id="addrow" type="button" value="Add field">

jQuery only run function for element that gets clicked

I got a small problem that i have no clue how to solve. This HTML/PHP code bellow gets different values from a database and outputs them into the different input fields.
The HTML/PHP bellow is one element, and multiple of them are made with different values from the database. Then i got a small javascript that calulates some different values from the values that are inputted. The problem is that i got lets say 5 elements, and only wants to calculate for one of them, but if i press the "btn-oppdater" button it calculates for all the different elements.
How do i make it only calculate for the element where the button is?
Script
$('.btn-oppdater').click(function(){
$(".kval_spill").each(function(){
var fieldShow = $(this).next('.kval_spill_inner');
var b_value_kval_1 = fieldShow.find('.b_value_kval_1')[0].value;
var b_odds_kval_1 = fieldShow.find('.b_odds_kval_1')[0].value;
var e_odds_kval_1 = fieldShow.find('.e_odds_kval_1')[0].value;
var gebyr_kval = '0.02'
var q_value = ((b_odds_kval_1 / (e_odds_kval_1 - gebyr_kval)) * b_value_kval_1);
var q_tap = (b_odds_kval_1 - 1) * b_value_kval_1 - (e_odds_kval_1 - 1) * q_value;
var q_value_fixed = q_value.toFixed(2);
var q_tap_fixed = q_tap.toFixed(2);
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
});
});
HTML/PHP
<?php while ($row = mysqli_fetch_assoc($result2)) { echo '
<form style="margin-top: 10px;" action="" method="post" class="">
<input type="hidden" class="kval_spill">
<div class="kval_spill_inner">
<input class="" type="hidden" name="id" value="'.$row['id'].'">
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_kamp_1" name="kval_kamp_1" value ="'.$row['kval_kamp_1'].'" placeholder="Kamp">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control b_value_kval_1" name="b_value_kval_1" value ="'.$row['b_value_kval_1'].'" placeholder="Spill verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control b_odds_kval_1" name="b_odds_kval_1" value ="'.$row['b_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_marked_1" name="kval_marked_1" value ="'.$row['kval_marked_1'].'" placeholder="Type marked">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control text-info q_value_1" name="q_value_1" value ="'.$row['q_value_1'].'" placeholder="Lay verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control e_odds_kval_1" name="e_odds_kval_1" value ="'.$row['e_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text">Tap</span>
</div>
<input type="text" class="form-control text-danger q_tap_1" name="q_tap_1" value ="'.$row['q_tap_1'].'" placeholder
="0.00" readonly>
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="col-auto">
<button type="button" class="btn btn-outline-secondary btn-oppdater">Regn ut</button>
</div>
</div>
</div>
</form>
<br>
'; }?>
Replace $(".kval_spill") with $(this).closest("form").find(".kval_spill").
But it looks like there's only one kval_spill and kvall_spill_inner in each form, so there's no need to use .each(). You can get rid of the .each() loop and just use:
var fieldShow = $(this).closest("form").find('.kval_spill_inner');
And instead of
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
you can write:
fieldShow.find('.q_value_1').val(q_value_fixed);
fieldShow.find('.q_tap_1').val(q_tap_fixed);

Calculate the total of item quantity into item price with dynamic HTML input fields using jQuery

I would like to calculate the total of item price multiple of item quantity using jQuery. I am using dynamic HTML input fields once I enter the amount it should calculate with quantity and give the total amount. please see the code below
My HTML Code
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".add_new_field"); //Fields wrapper
var add_button = $(".add_another_product"); //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
$(wrapper).append('<div class="add_new_field"><div class="row"><div class="col-md-4"><div class="form-group"><label class="col-form-label"> Enter Product Name</label><input type="text" class="form-control" name="pname[]" placeholder="Product Name" tabindex="1"/></div></div><div class="col-md-4"><div class="form-group"><label class="col-form-label"> No. of Pieces</label><input type="text" class="form-control" name="pcount[]" placeholder="Product Inventory" tabindex="2" /></div></div><div class="col-md-3"><div class="form-group"><label class="col-form-label"> Estimated Amount</label><input type="text" class="form-control" name="estamount[]" placeholder="Product Inventory" tabindex="2" /></div><p>Amount: <span id="Amount"></span></p></div><i class="fa fa-remove"></i></div></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$('#EstmTotal').blur(function() {
$('.add_new_field').each(function() {
$(this).find('#Amount').html($('#PCount(0)', this).val() * $('#EstmTotal(0)', this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" />
</div>
<p>Amount: <span id="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
please see the image for better understanding of the question
There is always an option to discuss
Full code here please try this. it will work according to your requirement.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
></script>
<script type="text/javascript">
function calculate(id){ console.log(id);
// $('#EstmTotal').on('blur',function(){
$(id).parents('.add_new_field').each(function() {
var count = $(this).find("#PCount").val();
var amount = $(this).find("#EstmTotal").val();
$(this).find('#Amount').html(count*amount);
});
// });
}
$(document).ready(function(){
$(".add_another_product").on('click',function(){
var html = '<div class="add_new_field">';
html += '<div class="row">';
html += '<div class="col-md-4">';
html += '<div class="form-group">';
html += '<label class="col-form-label"> Enter Product Name</label>';
html += '<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name"/></div></div>';
html += '<div class="col-md-4"><divclass="form-group"><label class="col-form-label"> No. of Pieces</label>';
html += '<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items"/>';
html += '</div></div>';
html += '<div class="col-md-3">';
html += '<div class="form-group">';
html += '<label class="col-form-label"> Estimated Amount</label><input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" onblur="calculate(EstmTotal)" />';
html += '</div><p>Amount: <span id="Amount"></span></p></div>';
html += '</div></div>';
$(this).before(html);
})
})
</script>
</head>
<body>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items"/>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" id="EstmTotal" onblur="calculate(EstmTotal)" placeholder="Estimated Amount of Each"/>
</div>
<p>Amount: <span id="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
</body>
</html>
Do not use same id for multiple elements, user class instead of id. See below code to get amount
$(function(){
$(document).on("blur", "div.row .col-md-3 input[name='estamount[]']", function(){
var $row = $(this).closest('.row'); // get parent row
var est = $(this).val(); // read estimante
var count = $row.find('input[name="pcount[]"]').val(); // read count
$row.find('span.Amount').html(est*count); // put product
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" placeholder="Product Name"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" placeholder="No.Of Items"/>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" placeholder="Estimated Amount of Each"/>
</div>
<p>Amount: <span class="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
I have made following changes in your code, where in you are finding the first element inside the array. You will get the desired results
$('#EstmTotal').blur(function() {
$('.add_new_field').each(function() {
var elem = $($('#PCount')[0]).val();
var elem2 = $($('#EstmTotal')[0]).val();
$(this).find('#Amount').html(elem * elem2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" />
</div>
<p>Amount: <span id="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
$('#EstmTotal').blur(function(){
$('.add_new_field').each(function() {
$(this).find('#Amount').html($('#PCount').val()*$('#EstmTotal').val());
});
});
JsFiddle source
I changed your code a bit. Now it checks on the blur event of both elements and it checks if both have a value. If both have it sets the calculated value. If not the div will me emptied.
Also parsing the value to a floating point number. You can change this to integers if you prefer that. The typing checking to number will be same for integers. I round the number down to 2 decimals, mainly to get around floating point number precision issues.
Last, since i thought you will have the ability to create more rows dynamically I made the blur event delegated by your .add_new_field element. This assumes your
.add_new_field is a static element. If not change this to the closest static parent of your row. For this I also changed some id selectors to class selectors because id's need to be unique.
$('.add_new_field').on('blur', '.EstmTotal, .PCount', function() {
$(this).closest('.row').each(function() {
var pcCount = parseFloat($(this).find('.PCount', this).val());
var estTotal = parseFloat($(this).find('.EstmTotal', this).val());
if (typeof pcCount === 'number' && pcCount && typeof estTotal === 'number' && estTotal) {
var calculatedValue = pcCount * estTotal;
calculatedValue = Math.round(calculatedValue * 100) / 100;
$(this).find('.Amount').text(calculatedValue);
} else {
$(this).find('.Amount').text('');
}
});
});
$('.add_another_product').on('click', function(){
$('.add_new_field').append($('.row').first().clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" placeholder="Product Name" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control PCount" name="pcount[]" placeholder="No.Of Items" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control EstmTotal" name="estamount[]" placeholder="Estimated Amount of Each" />
</div>
<p>Amount: <span class="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>

Vue.js: How to generare multiple dynamic ID's with a defined pattern

This is a twin post to Function that generates multiple dynamic ID's with a defined pattern.
The reason for this is that I am creating an application in which I am supposed to use Vue.js. I am learning on the fly, the syntax in the solution of the first question was very close to how it would look in a Vue template, I decided that I should try to recode it.
The finished Vue Component should work like this jsFiddle (by #DeepuReghunath). How do I to achieve this? The ID's has to be dynamic, so does the radio button names!
One of the problems I encountered while doing this is that the Add Question button, that generates new divs doesn't work as intended. As you can see, there is both javaScript and Vue in the same class. I know that it is not ultimate, but since I cant hide and show root components with Vue there isn't much to do about it.
Here you can see the jsFiddle with the same code as bellow!
HTML
<div id="singleQuestionModule">
<form class="form-group">
<div class="d-flex justify-content-center">
<fieldset class=" form-group row">
<div id="testContainer">
<testcomponent></testcomponent>
</div>
</fieldset>
</div>
</form>
</div>
Vue.js + JavaScript
let name = 1;
let theTitle;
function testDetails() {
theTitle = document.getElementById("titleInput").value;
document.getElementById("testH1").innerHTML = theTitle;
document.getElementById("titleLabel").innerHTML = "Do you want to change the title?";
$("#removableText").hide();
$("#singleQuestionModule").show();
$("#tCreateTest").css('height', '50vh');
let aQuestion = document.getElementById('addQuestion');
if (aQuestion.style.display ==
= 'none') {
aQuestion.style.display = 'block';
}
}
Vue.component('testcomponent', {
template: `
<div>
<form class="form-group">
<div class="d-flex justify-content-center">
<fieldset class=" form-group row">
<span class="module">
<div class="input-group input-group">
<label id="wQuestionLabel" class="form-control-label" for="wQuestion">Question:</label>
</div>
<div class="form-group row">
<div class="input-group input-group">
<!-- The Question Inputfield that needs ID-->
<input type="text" class="form-control" :id="testTitle + 'Q' + name" style="width: 540px;">
</div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<label id="questionOptions" class="form-control-label"
for="wQuestion">Enter avaible options:</label>
</div>
</div>
<!-- The radiobuttons and option inputfields that needs ID's-->
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" :name="testTitle + 'rg' + name" :id="testTitle + 'Q' + name + 'Q'" value="1" aria-label="">
</span>
<input type="text" :id="testTitle + 'Q' + name + 'input' + '4'" class="form-control" aria-label="" style="width: 540px;"> </div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" :name="testTitle + 'rg' + name" :id="testTitle + 'Q' + name + 'Q'" value="2" aria-label="">
</span>
<input type="text" :id="testTitle + 'Q' + name + 'input' + '4'" class="form-control" aria-label="" style="width: 540px;"> </div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" :name="testTitle + 'rg' + name" :id="testTitle + 'Q' + name + 'Q'" value="3" aria-label="">
</span>
<input type="text" :id="testTitle + 'Q' + name + 'input' + '4'" class="form-control" aria-label="" style="width: 540px;"> </div>
</div>
<div class="form-group row">
<div class="input-group input-group">
<span class="input-group-addon">
<input type="radio" :name="testTitle + 'rg' + name" :id="testTitle + 'Q' + name + 'Q'" value="4" aria-label="">
</span>
<input type="text" :id="testTitle + 'Q' + name + 'input' + '4'" class="form-control" aria-label="" style="width: 540px;">
</div>
</div>
</span>
<span class="options-label"></span>
<br>
<div class="form-group row">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success" id="radioAddQuestion">
<input type="radio" #click="name++" name="options" autocomplete="off">Add
Question</label>
<label class="btn btn-success">
<input type="radio" name="options" id="radioSaveTest" value="saveTest()" autocomplete="off">Save
Test </label>
</div>
</div>
</fieldset>
</div>
</form>
</div>
`,
data: function() {
return {
name: name,
testTitle: theTitle,
}
}
});
new Vue({
el: '#testContainer',
data: {
seen: true
},
});
Made some changes to the template and vue object. variable dynamicID ,count and addElement() method are added extra from my side to achieve this.
data: function() {
return {
testTitle: "onlineexam",
input: "input",
rg: "rg",
Q: "Q",
O: "O",
one: "1",
two: "2",
three: "3",
four: "4",
name:dynamicID
}
}});
new Vue({
el: '#testContainer',
data: {
seen: true,
count:1
},
methods: {
addElement: function () {
dynamicID++;
this.count++;
}}
});
Jsfiddle :https://jsfiddle.net/d60j70j6/
Now the question number and question input field id are dynamically generating with different value.
You might be thinking about this wrong. Wanting to give things ids is a sign that you're not thinking vue yet. Vue doesn't need ids. Anything that's a repeating element should be in its own component, so you'll be wanting a question component. Then, think about your store first, then build the interface to present the info. So if you're writing a test app, near the top level of your store, you'll want an array of questions, each question having an array of answers...
var vueStore = {
questions : [
{ questionText : 'qqdf', answers : [] },
{ questionText : 'gj', answers : [] },
{ questionText : 'zerh', answers : [] }
]
}

How to use ternary operator to change value of ng-model in AngularJS?

I have one text field and one checkbox. If checkbox is true I want value from address field to become after the checkbox, if false the field should be empty. I tried ternary operator with ng-class and many more, but no luck. What would be the best and working solution for that?
jsfiddle
<form name="form" ng-app>
<div class="form-group form-group-lg required">
<label class="col-md-2 control-label">Address:</label>
<div class="col-md-10" ">
<input type="text " name="address " class="form-control " ng-model="address " ng-minlength="4 " placeholder="Address " required>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-md-2 control-label">Return Address</label>
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon">
<!--condition ? first_expression : second_expression; -->
<input type="checkbox" ng-model="isReturnAddress" ng-change="">
</span><!--condition ? first_expression : second_expression; -->
<input type="text" class="form-control" ng-model="address">
</div>
{{isReturnAddress}}
</div>
</div>
<button type="submit " class="btn btn-primary btn-large " ng-click="submitted=true ">Submit</button>
you should use two input elements in this case. Like
<input ng-if="isReturnAddress" type="text" class="form-control" ng-model="address">
<input ng-if="!isReturnAddress" type="text" class="form-control">
and in your controller, please check
if($scope.isReturnAddress){
var address = $scope.address;
}
See working fiddle here

Categories