when click on the option add inputs with option value - javascript

<script>
function run() {
document.getElementById("ip").value= document.getElementById("Ultra").value;
}
</script>
<script>
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><span class="lb">Ip Address:</span><input id="ip" type="text" name="ip[]" size="4" value="'+frm.add_ip.value+'" required placeholder="192.168.0.1:80" class="form-control wid2" /> <input type="button" value="-" onclick="removeRow('+rowNum+');" class="remove" style=" width:9%;"></p>';
jQuery('#itemRows').append(row);
frm.add_ip.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="myformp">
<form method="get" class="myformp2" id="ipForm">
<div id="itemRows">
<span class="lb">Ip Address:</span><input class="form-control wid2 " type="text" name="add_ip" size="4" required placeholder="192.168.0.1:80" title="ip address" id="ip"/> <input type="button" value="+" class="add" style=" width:9%;" />
</div>
<button type="submit" class="btn btn-default mybtn2">save</button>
<div class="clear"></div>
<select id="Ultra" onchange="run()"> <!--Call run() function-->
<option onclick="addRow(this.form);"value="0">Select</option>
<option onclick="addRow(this.form);"value="8">text1</option>
<option onclick="addRow(this.form);"value="5">text2</option>
<option onclick="addRow(this.form);"value="4">text3</option>
</select>
</form>
</div>
i want when click on option input add and option value replace with input value but when click on the option more than one it dont replace and i must click on another option then click it can work!

You are setting the value of the newly created input to frm.add_ip.valuŠµ which is the value of the input, not the select.
Since it's in a form you're already using, you can access the select (and it's value) using
form.Ultra.value
which gives you the actual value (0,8,5,4), or you can access it via jquery with
$("#Ultra").val()
which gives you the same thing.
That said, you're generating all the other text-boxes with the same id of ip. Since you already give specific id's to the paragraph tags, you should use the exact approach with the text-boxes as well.
<script>
function run() {
document.getElementById("ip").value= document.getElementById("Ultra").value;
}
</script>
<script>
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><span class="lb">Ip Address:</span><input id="ip" type="text" name="ip[]" size="4" value="'+$("#Ultra").val()+'" required placeholder="192.168.0.1:80" class="form-control wid2" /> <input type="button" value="-" onclick="removeRow('+rowNum+');" class="remove" style=" width:9%;"></p>';
jQuery('#itemRows').append(row);
frm.add_ip.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="myformp">
<form method="get" class="myformp2" id="ipForm">
<div id="itemRows">
<span class="lb">Ip Address:</span><input class="form-control wid2 " type="text" name="add_ip" size="4" required placeholder="192.168.0.1:80" title="ip address" id="ip"/> <input type="button" value="+" class="add" style=" width:9%;" />
</div>
<button type="submit" class="btn btn-default mybtn2">save</button>
<div class="clear"></div>
<select id="Ultra" onchange="run()"> <!--Call run() function-->
<option onclick="addRow(this.form);"value="0">Select</option>
<option onclick="addRow(this.form);"value="8">text1</option>
<option onclick="addRow(this.form);"value="5">text2</option>
<option onclick="addRow(this.form);"value="4">text3</option>
</select>
</form>
</div>

remove addRow and run methods and add this event handler. You don't need to handle click on option separately, onchange on select is enough. You are not using the values of options anyways.
$( "#Ultra" ).change( function(){
$( "#ip" ).val( $( this ).val() );
var row = '<p id="rowNum'+rowNum+'"><span class="lb">Ip Address:</span><input id="ip" type="text" name="ip[]" size="4" value="'+frm.add_ip.value+'" required placeholder="192.168.0.1:80" class="form-control wid2" /> <input type="button" value="-" onclick="removeRow('+rowNum+');" class="remove" style=" width:9%;"></p>';
$( '#itemRows' ).append(row);
} );

function run() {
document.getElementById("ip").value = document.getElementById("Ultra").value;
}
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '"><span class="lb">Ip Address:</span><input id="ip" type="text" name="ip[]" size="4" value="' + frm.add_ip.value + '" required placeholder="192.168.0.1:80" class="form-control wid2" /> <input type="button" value="-" onclick="removeRow(' + rowNum + ');" class="remove" style=" width:9%;"></p>';
jQuery('#itemRows').append(row);
frm.add_ip.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="myformp">
<form method="get" class="myformp2" id="ipForm">
<div id="itemRows">
<span class="lb">Ip Address:</span><input class="form-control wid2 " type="text" name="add_ip" size="4" required placeholder="192.168.0.1:80" title="ip address" id="ip"/> <input type="button" value="+" class="add" style=" width:9%;" />
</div>
<button type="submit" class="btn btn-default mybtn2">save</button>
<div class="clear"></div>
<select id="Ultra" onchange="run()"> <!--Call run() function-->
<option onclick="addRow(this.form);"value="0">Select</option>
<option onclick="addRow(this.form);"value="8">text1</option>
<option onclick="addRow(this.form);"value="5">text2</option>
<option onclick="addRow(this.form);"value="4">text3</option>
</select>
</form>
</div>
Some thing wrong !

Related

How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>

Get all values in my added column using PHP (codeigniter)

I am studying the dbforge, and trying to apply it with my website. My basis or guide is the localhost/phpmyadmin where you will create a new table, i am done with the part of table name, name,type,attribute,length of the column and also the adding the column(see the picture below) .
Question: How can I retrieve all the post value?
Note: I tried to echo json_encode($_POST); im only getting 1 value.
View
<form id="new-table">
<div class="col-md-6">
<label>Table Name:</label>
<input type="hidden" name="type" value="new_table">
<input type="text" class="form-control border-input" name="table_name" id="table_name"><br>
<div class="text-danger" id="table_name_error"></div>
</div>
<!-- col-md-6 -->
<div class="col-md-3">
<label>Columns:</label>
<!-- <input type="text" class="form-control border-input" name="table_name" id="table_name"> -->
<input type="text" class="form-control border-input" id="number_of_column" >
</div>
<div class="col-md-3">
<br>
<button type="button" class="btn btn-info btn-fill btn-wd" onclick="addColumn()">Add</button>
</div>
<!-- col-md-3 -->
</div> <!-- row-->
<!-- <input type='button' value='Add Children' id='addButton' class="btn btn-sm btn-primary"> -->
<div class="row">
<div class="col-md-2">
<h6>Name</h6>
<input type="text" class="form-control border-input" name="field_name" id="field_name">
<div class="text-danger" id="field_name_error"></div>
</div>
<div class="col-md-2">
<h6>Type</h6>
<select class="form-control border-input" name="field_type" id="field_type">
<option value="volvo">Varchar</option>
<option value="saab">Int</option>
<option value="mercedes">Date</option>
<option value="audi">Text</option>
</select>
</div>
<div class="col-md-2">
<h6>Length/Value</h6>
<input type="text" class="form-control border-input" name="field_length" id="field_length">
<div class="text-danger" id="field_length_error"></div>
</div>
<div class="col-md-2">
<h6>Default</h6>
<input type="text" class="form-control border-input" name="field_default" id="field_default">
<div class="text-danger" id="field_default_error"></div>
</div>
<div class="col-md-2">
<h6>Attributes</h6>
<input type="text" class="form-control border-input" name="field_attributes" id="field_attributes">
<div class="text-danger" id="field_attributes_error"></div>
</div>
<div class="col-md-2">
<h6>Null</h6>
<input type="text" class="form-control border-input" name="field_null" value="null"><br>
<div class="text-danger" id="field_null_error"></div>
</div>
<div id="append">
<div id="TextBoxDiv1">
</div>
</div>
</div> <!-- row -->
<div class="text-right">
<button type="submit" class="btn btn-info btn-fill btn-wd">Update Profile</button>
</div>
</div>
<div class="clearfix"></div>
</form>
Controller
JS
My creating new column function
function addColumn()
{
var i = 0;
var columns = document.getElementById("number_of_column").value;
for(i=1;i<=columns;i++)
{
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' );
newTextBoxDiv.after().html('<div class="col-md-2">'+
'<label>Name</label>'+
'<input type="text" class="form-control border-input" name="field_name[]" id="field_name[]">'+
'<div class="text-danger" id="children_fname_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Type</h6>'+
'<select class="form-control border-input" name="field_type[]" id="field_type[]">'+
'<option value="volvo">Varchar</option>'+
'<option value="saab">Int</option>'+
'<option value="mercedes">Date</option>'+
'<option value="audi">Text</option>'+
'</select>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Length/Value</h6>'+
'<input type="text" class="form-control border-input" name="field_length[]" id="field_length[]">'+
'<div class="text-danger" id="field_length_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Default</h6>'+
'<input type="text" class="form-control border-input" name="field_default" id="field_default">'+
'<div class="text-danger" id="field_default_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Attributes</h6>'+
'<input type="text" class="form-control border-input" name="field_attributes" id="field_attributes">'+
'<div class="text-danger" id="field_attributes_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Null</h6>'+
'<input type="text" class="form-control border-input" name="field_null" id="field_null"><br>'+
'<div class="text-danger" id="field_null_error"></div>'+
'</div>'
);
newTextBoxDiv.appendTo("#append");
}
document.getElementById("number_of_column").value = "";
}
** My submit form**
$(document).ready(function(){
$("#new-table").on('submit',function(e){
$.ajax({
url: base_url+"formsubmit/new_form_submit",
type: "POST",
data: $(this).serialize(),
success:function(data)
{
var result = JSON.parse(data);
if(result === "success")
{
$("h5").html("");
success_message("#success-message-edit-content-1","Update Successfully!");
window.setTimeout(function(){location.href=base_url+"administrator/view_content"},2000);
}
else{
$("#table_name_error").html(result.table_name_error);
$("#field_name_error").html(result.field_name_error);
$("#field_type_error").html(result.field_type_error);
$("#field_length_error").html(result.field_length_error);
}
},
error: function(data) {
alert('error');
}
})
e.preventDefault();
})
})
In your code, I see you already have an input with name="field_name" and in the addColumn()
function you are also adding another input with the same name.
When you have a input named "field_name" in the form and later you again dynamically add another input with the same name again, they replaces one another and there is only one of their value present in the post data with that same name.
You can use array inputs here, like
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
You will get the Post array like:
Array
(
[field_name] => Array
(
[0] => fv1
[1] => fv2
....
)
[field_type] => Array
(
[0] => ftv1
[1] => ftv12
...
)
)
So for parsing:
$fields_array = array();
$no_of_fields = isset($_POST['field_name'])? count($_POST['field_name']) : 0;
for ($i=1; $i<=$no_of_fields; $i++) {
$tmp = array();
if (isset($_POST['field_name'][$i])) $tmp[] = $_POST['field_name'][$i];
if (isset($_POST['field_type'][$i])) $tmp[] = $_POST['field_type'][$i];
...
if (!empty($tmp)) $fields_array[] = array();
}
It is a little bit errorprone(assuming field_name, field_type will have arrays of same number of elements, if one is missing the parallel serial among them will be corrupted) approach.
Better to use counter for the fields.
For example:
<input name="no_of_fields" value="1"/>
Which's value will be increased in each addition.
And your form be like:
<input name="field_name_1" .../>
<input name="field_type_1" .../>
...
<input name="field_name_2" .../>
<input name="field_type_2" .../>
...
<input name="field_name_3" .../>
<input name="field_type_3" .../>
...
For parsing on the server side, you can go for:
$fields_array = array();
$no_of_fields = isset($_POST['no_of_fields'])? intval($no_of_fields) : 0;
if ($no_of_fields > 0) {
for ($i=1; $i<=$no_of_fields; $i++) {
$tmp = array();
if (isset($_POST['field_name_'.$i])) $tmp[] = $_POST['field_name_'.$i];
if (isset($_POST['field_type_'.$i])) $tmp[] = $_POST['field_type_'.$i];
...
if (!empty($tmp)) $fields_array[] = array();
}
}
// Now process/output the $fields_array;

Jquery Add string from button value into an input field

I'm trying to add some string from button that has a value into an input field but doesn't work ..
here's jquery code, can anyone please fix it ?
<script type="text/javascript">
$(function () {
$('#button1').on('click', function () {
var text = $('#kategori');
text.val(text.val() + $('#button1')(text.val());
});
});
</script>
and here html + php code
<div class="form-group">
<label for="kategori">
Kategori:
</label>
<input type="text" class="form-control" id="kategori" name="kategori" />
</div>
<?php $query = $this->db->query("SELECT * from kategori_elibrary");
$hasil = $query->result();
?>
<div class="btn-group">
<?php
foreach($hasil as $row){
echo '<button type="button" class="btn btn-primary" id="button1" value="'.$row->kategori.'">'.$row->kategori.'</button>';
} ?>
</div>
$('#button1').on('click', function () {
$('#kategori').val($('#kategori').val() + $('#button1').attr('value'));
});
Are you need like this: button text added into textbox at the time of click.apply $(this).html() button value add to texbox
$('#button1').on('click', function () {
$('#kategori').val($('#kategori').val()+$(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="kategori">
Kategori:
</label>
<input type="text" class="form-control" id="kategori" name="kategori" />
<button id="button1">before</button>
</div>
<div class="btn-group">
</div>
Alternate
if you create the button like
`<input type="button" id="button1" value="before">
in jquery use with. $(this).val()
with the help of data-attributes which makes the button markup look like this:
<button type="button" class="btn btn-primary" id="button1" data-value="Food">
Food
</button>
Then you can use this script: UPDATED
// NOTE: This will get all button elements of type button
// if you have other elements of this markup change the selector to:
// $('button[id^="button"]')
$('button:button').on('click', function() {
var $target = $('#kategori'),
text = $('#kategori').val(),
buttonVal = $(this).data('value');
$target.val(`${text}${buttonVal}`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="kategori">
Kategori:
</label>
<input type="text" class="form-control" id="kategori" name="kategori" />
</div>
<button type="button" class="btn btn-primary" id="button1" data-value="Food">Food</button>
<button type="button" class="btn btn-primary" id="button2" data-value="Tools">Tools</button>
<button type="button" class="btn btn-primary" id="button2" data-value="Anything">Anything</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="kategori">
Kategori:
</label>
<input type="text" class="form-control" id="kategori" name="kategori" />
</div>
<div class="btn-group">
<button type="button" class="btn btn-primary" id="button1" value="1">1</button>
<script type="text/javascript">
$(function () {
$('#button1').on('click', function () {
var text = $('#kategori');
text.val(text.val() + $('#button1').val());
});
});
</script>
<button type="button" class="btn btn-primary" id="button2" value="2">2</button>
<script type="text/javascript">
$(function () {
$('#button2').on('click', function () {
var text = $('#kategori');
text.val(text.val() + $('#button2').val());
});
});
</script>
</div>
$( '.button-input' ).on( 'click', function () {
$( '#kategori' ).val( $(this).val() );
} );
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="form-group">
<label for="kategori">Kategori:</label>
<input type="text" class="form-control" id="kategori" name="kategori" />
</div>
<?php
$query = $this->db->query("SELECT * from kategori_elibrary");
$hasil = $query->result();
?>
<div class="btn-group">
<?php foreach ( $hasil as $row ) { ?>
<input type="button" class="btn btn-primary button-input" id="button<?= $row->id; ?>" value="<?= $row->kategori; ?>" />
<?php } ?>
</div>

Cannot create multiple text box with different id using JavaScript and jQuery

I am unable create multiple text field dynamically using JavaScript and jQuery. My code is below:
<div class="col-md-3">
<div class="form-group">
<label for="ques">No of questions</label>
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" type="text">
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Questions</label>
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();">
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>
<div class="text-left" id="intro-add" style="display:none">
<input type="button" name="" class="btn btn-sm btn-info" value="Add">
</div>
</div>
</div>
<div id="container">
<div class="form-group" style="margin-top:5px;display:block" id="introBox0" >
<div>
<input type="text" style="width: 77.5%;float:left; margin-bottom:5px; margin-right:5px;" class="form-control inptbox0" id="scaleans00" name="labelname" placeholder="Answer" value="">
<input type="button" style="line-height:13px; margin-right:2px; margin-top:5px; float:left;" class="btn btn-danger btn-sm" name="labelminus" id="labelminus" value="-">
<div class="text-left" id="intro-add" style="display:block">
<input type="button" name="" class="btn btn-sm btn-info" value="Add" onclick="addMore(0,0)">
</div>
</div>
</div>
<hr>
</div>
Here user will create multiple question section and each question section user has to create multiple field using add button and will delete using minus button . Each question field should unique id.Suppose in section one there are 3 input field then its ids should be like this scaleans00,scaleans01,scaleans02... and for section two these should be scaleans10,scaleans11,scaleans12... and so on.
Here is my JavaScript code:
<script>
function addQuestionField() {
var get = $("#ques").val();
for (var i = 1; i < get; i++) {
$('#container').append('<div class="form-group dyn" style="margin-top:5px;display:block" id="introBox'+i+'"><div><input type="text" style="width: 77.5%;float:left; margin-bottom:5px; margin-right:5px;" class="form-control inptbox'+i+'" id="scaleans'+i+'0" name="labelname" placeholder="Answer" value=""><input type="button" style="line-height:13px; margin-right:2px; margin-top:5px; float:left;" class="btn btn-danger btn-sm" name="labelminus" id="labelminus" value="-"><div class="text-left" id="intro-add" style="display:block"><input type="button" name="" class="btn btn-sm btn-info" value="Add" onclick="addMore('+i+',0)"></div></div></div><hr>');
}
}
function deleteQuestionField() {
var textareas = $('#container .dyn');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
function addMore(parent,child){
var mainDiv='#introBox'+parent;
$(mainDiv).append('<div><input type="text" style="width: 77.5%;float:left; margin-bottom:5px; margin-right:5px;" class="form-control inptbox'+parent+'" id="scaleans" name="labelname" placeholder="Answer" value="">'+'<input type="button" style="line-height:13px; margin-right:2px; margin-top:5px; float:left;" class="btn btn-danger btn-sm" name="labelminus" id="labelminus" value="-"></div>');
repopulate(parent);
}
function repopulate(k){
var mainId='.inptbox'+k;
var j=0;
$(mainId).each(function(i, e) {
if(i==0){
$(this).attr('id', 'scaleans' + i+j);
$(this).next().attr('onClick', function(old, n) {
return 'removeThis(' + i + ','+j+')';
})
$(this).next().attr('id', function(old, n) {
return 'labelminus' + i+j;
});
}else{
$(this).attr('id', 'scaleans' + i+(j+1));
$(this).next().attr('onClick', function(old, n) {
return 'removeThis(' + i + ','+(j+1)+')';
})
$(this).next().attr('id', function(old, n) {
return 'labelminus' + i+(j+1);
});
}
})
}
function removeThis(r,t) {
$("#scaleans" + r+t).remove();
$("#labelminus" + r+t).remove();
repopulate();
}
</script>
Here I can not create as per my requirement. Here is my full code.
I will be explaining to you what is going on with the current code you have put in Plunker
function addQuestionField() {
var get = $("#ques").val();
for (var i = 1; i < get; i++) {
In Your method addQuestionFiled(), the value retrieved into get variable is not truthy, if you are not entering any value into the
number of questions
textfield. Hence the html will not get appended
Fill in the number of question as 2, and then click add it will keeping on appending the html to container div as the 'var get' will have the value 2 and 'var i' is less than 'var get'

Cannot delete the radio button input field dynamically using JavaScript/jQuery

I am creating multiple text area, radio button field and drop down list by click on a plus button. Here I need when user will click on minus button the last all 3 type item should delete but it's not happening like that.
Here is my code:
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" type="text">
<label>Questions</label>
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();">
<input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
<div id="container">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
</div>
<div class="col-md-9">
<div style="margin-top:37px;">
<div style="float:left; margin-right:10px;">
<input type="radio" name="answer_type0" id="answer_type0" onClick="selectScale(this.value,'0');">
</div>
<div style="float:left; margin-top:-10px;display:none;" id="scaleid0">
<select class="form-control" id="nscale0" name="noofscale0">
<option value="">Select Answer Type</option>
<option value="1">Cuttuck</option>
<option value="1">BBSR</option>
</select>
</div>
</div>
</div>
The JavaScript code is given below.
function addQuestionField(){
var get =$("#ques").val();
if(get===null || get===''){
alert('Please add no of questions');
}else{
for(var i=1;i<get;i++){
$('#container').append('<div class="row"><div class="col-md-3"><div class="form-group"><textarea class="form-control" name="questions'+ i +'" id="questions'+ i +'" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div> <div class="col-md-9" ><div style="margin-top:37px;"><div style="float:left; margin-right:10px;"> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');"></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="1" >Cuttuck</option><?php } ?></select></div><div style="clear:both;"></div></div></div><div>');
}
}
}
function deleteQuestionField(){
var get =$("#ques").val();
var textareas = $('#container textarea');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
Here when I am clicking - button only the last text area is removing. But I need to delete the respective radio button and drop down list(if exist) with text area. Here the total plunkr code is present.
Add a wrapper class for the input set all together and remove it on delete, always in templating, try to use wrapper selector to isolate blocks of html code
$('#container').append('<div class="row dyn">
https://plnkr.co/edit/kBWcs6zUmMndB3RwXMcF?p=preview
Try this and please close your div properly i think You forgot to put one div closing tag.
function deleteQuestionField(){
var get =$("#ques").val();
var textareas = $('#container').find('textarea');
if (textareas.length !== 0) {
$('#container div.row:last-child').remove();
$('#ques').val(textareas.length - 1);
}
}
you can delete the last row which you added dynamically and which contains the textarea, radio button and dropdown list.
function deleteQuestionField(){
$("#container>row").last().remove();
}
This worked for me,
HTML :
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" type="text">
<label>Questions</label>
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+">
<input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-">
<div id="container">
</div>
JS (jQuery) :
$(document).ready(function(){
$('#plus').click(function(){
var get =$("#ques").val();
if(get===null || get===''){
alert('Please add no of questions');
}else{
for(var i=1;i<=get;i++){
$('#container').append('<div class="row"> <div class="col-md-9" ><div style="margin-top:37px;"><div style="float:left; margin-right:10px;"> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');"></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="1" >Cuttuck</option><?php } ?></select></div><div class="col-md-3"><div class="form-group"><textarea class="form-control" name="questions'+ i +'" id="questions'+ i +'" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div><div style="clear:both;"></div></div></div><div>');
}
}
});
$('#minus').click(function(){
var get =$("#ques").val();
var textareas = $('#container textarea');
var radiobtns = $('#container input');
if (textareas.length !== 0) {
textareas.last().remove();
radiobtns.last().remove();
$('#ques').val(textareas.length - 1);
}
});
});
See the jsfiddle

Categories

Resources