I want to make an editable dropdown, and on double click of the data the dropdown should appear and make populate the options from and external JS, this should be made to run more than once.
The following is the HTML for this
<div class="tabbable">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<table id='table-draggable1'>
<tbody class="connectedSortable">
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
<tr>
<td>156</td>
<td>668</td>
<td>100.95</td>
<td class="master">100.95</td> //editable dropdown
</tr>
<tr>
<td class="desc">256</td>
<td>668</td>
<td>100.95</td>
<td class="master">100.95</td> // ondblclick should be editable
</tr>
</tbody>
</table>
</div>
</div>
</div>
The jquery which i tried for making the dropdown editable
$document.ready(function ()
{
dropdown();
$(function ()
{
$(".master").dblclick(function (e)
{
e.stopPropagation();
var currentEle = $(e.target);
var value = $(e.target).html();
console.log($(e.target));
if ($.trim(value) === "")
{
$(currentEle).data('mode', 'add');
}
else
{
$(currentEle).data('mode', 'edit');
}
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value)
{
$(currentEle).html("<select class='master'></select>");
var mode = $(currentEle).data('mode');
alert(mode);
$(".master").focus();
$(".master").keyup(function (event)
{
if (event.keyCode == 13)
{
$(this).parent().html($(this).val().trim());
$(".master").remove();
}
});
}
$(document).click(function (e)
{
if ($(".master") !== undefined)
{
if ($(".master").val() !== undefined)
{
$(".master").parent().html($(".master").val().trim());
$(".master").remove();
}
}
});
}
function dropdown()
{
var resp = "<option>" + 1 + "</option>"; //this should be populated in dropdown
$(".master").html(resp);
}
}
});
http://jsfiddle.net/tXakG/
You can accomplish this by using the datalist tag in HTML5.
<input type="text" name="product" list="productName"/>
<datalist id="productName">
<option value="a">Apple</option>
<option value="o">Orange</option>
<option value="b">Banana</option>
</datalist>
If you double click on the input text in the browser a list with the defined option will appear.
Added using javascript : data is conceded that taken from server through ajax
http://jsfiddle.net/rajaveld/7yM6V/
Else you can use jquery :
You can refer is jQuery UI for the same.
Related
I'm using a code that I also found here that filters a table based on a dropdown selection. I'm not well-versed with JQuery/Javascript. My Question is how can I "show all" the data using this code snippet:
dropdown:
Show All
Done
On-going
Not yet started
$(document).ready(function($) {
$('#selectField').change(function() {
var selection = $(this).val();
var dataset = $('table').find('tr');
dataset.show();
dataset.filter(function(index, item) {
return $(item).find('td:nth-child(1)').text().split(',').indexOf(selection) === -1;
}).hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='selectField'>
<option value=" "> Show All </option>
<option value="Done"> Done </option>
<option value="On-going"> On-going</option>
<option value="Not yet started"> Not yet started </option>
</select>
<table border="2">
<tr>
<td>Done</td>
</tr>
<tr>
<td>On-going</td>
</tr>
<tr>
<td>Done</td>
</tr>
<tr>
<td>Not yet started</td>
</tr>
<tr>
<td>Not yet started</td>
</tr>
</table>
You can check the value of dropdown and then filter it
like
$(document).ready(function($) {
$('#selectField').change(function() {
var selection = $(this).val();
var dataset = $('table').find('tr');
var unSelectedData;
dataset.show();
if (selection !== ' ') {
var unSelectedData = dataset.filter(function(index, item) {
return $(item).find('td:nth-child(1)').text().split(',').indexOf(selection) === -1;
})
}
if (unSelectedData) {
unSelectedData.hide();
}
});
});
$(document).ready(function($) {
$('#selectField').change(function() {
var selection = $(this).val();
var dataset = $('table').find('tr');
var unSelectedData;
dataset.show();
if (selection !== ' ') {
var unSelectedData= dataset.filter(function(index, item) {
return $(item).find('td:nth-child(1)').text().split(',').indexOf(selection) === -1;
})
}
if (unSelectedData) {
unSelectedData.hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='selectField'>
<option value=" "> Show All </option>
<option value="Done"> Done </option>
<option value="On-going"> On-going</option>
<option value="Not yet started"> Not yet started </option>
</select>
<table border="2">
<tr>
<td>Done</td>
</tr>
<tr>
<td>On-going</td>
</tr>
<tr>
<td>Done</td>
</tr>
<tr>
<td>Not yet started</td>
</tr>
<tr>
<td>Not yet started</td>
</tr>
</table>
The solution is to avoid search action when selection is same value as "Show all" option which is " "
I've updated the jQuery code as below, and it works :
$(document).ready(function($) {
$('#selectField').change(function() {
var selection = $(this).val();
var dataset = $('table').find('tr');
dataset.show();
dataset.filter(function(index, item) {
if (selection !== ' ') {
return $(item).find('td:nth-child(1)').text().split(',').indexOf(selection) === -1;
}
}).hide();
});
});
I just want to delete dynamically created row, but iam unable to call the function using jquery and javascript.
const dynamic_JS = ({ sno, optionVal, price }) => `<tr><td>${sno}</td> <td><select name="selectProduct" class="form-control" selected="${optionVal}"><option value="0"> -- Select One --</option><option value="1"> IPhone </option><option value="2"> MAC </option><option value="3"> Windows </option></select></td> <td><input type="text" class="form-control" value="${price}" title="" ></td> <td><button type="button" class="remove-row btn btn-info glyphicon glyphicon-remove" ></button></td> </tr>`;
// onclick=\'removeRow(this)\'
//window.onload=function(){}
$(document).ready(function() {
var template_add = $('#hidden-template').text();
function render(props) {
return function(tok, i) {
return (i % 2) ? props[tok] : tok;
};
}
var items = [ { sno: '1', optionVal: '0', price: '0' } ];
var dynamic_HTML = template_add.split(/\$\{(.+?)\}/g);
$('tbody').append(items.map(function(item) {
return dynamic_HTML.map(render(item)).join('');
}));
});
// https://stackoverflow.com/a/35592412/5081877
$('#number_only').on('input propertychange', function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
$('.add-new').on('click', function () {
$("#productTable").each(function () {
var tr_last = $('tbody > tr:last', this).clone();
var td_no = tr_last.find('td:first');
var serialNumber = parseInt(td_no.text()) + 1;
// https://stackoverflow.com/a/6588327/5081877
var tr_first_input = $('tbody > tr:first > td:nth-child(3) > input');
var tr_first_price = parseFloat(tr_first_input.val()) || 0;
console.dir( tr_first_price );
totalamount += tr_first_price;
$('#totalAdd').text(totalamount);
var tr_first_selected = $('tbody > tr:first > td:nth-child(2) > select option').filter(":selected");
// option:selected | .find(":selected") ~ .text(), ~.attr('value');
var selectedValue = tr_first_selected.val(), optionText = tr_first_selected.text().trim();
console.log(' Text : ', optionText );
console.log('Value : ', selectedValue );
// https://stackoverflow.com/a/39065147/5081877
$('tbody', this).append([
{ sno: serialNumber, optionVal: selectedValue, price: tr_first_price }
].map(dynamic_JS).join(''));
var last_optionSel = $('tbody#mainBody > tr:last > td:nth-child(2) > select');
last_optionSel.val( selectedValue );
tr_first_input.val( 0 );
// https://stackoverflow.com/a/13089959/5081877
var first_optionSel = $('#productOption');
//$('tbody > tr:first > td:nth-child(2) > select ');
first_optionSel.val( 0 );
return;
});
});
var totalamount = 0; // tr#mainRow
$('table#productTable > tbody ').on('keyup', 'input', function(e) {
var total =
$(e.delegateTarget)
.find('input')
.map(function() {
return parseFloat($(this).val()) || 0;
})
.get()
.reduce(function(a, b) {
return a + b;
});
$('#total').text(total);
});
<!-- Remove row - javascript & Jquery -->
$('.remove-row').on('click', function () {
$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove();
});
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<table id="productTable" class="table table-hover table-bordered">
<thead>
<tr>
<th>No.</th><th>Product</th><th>Price</th><th>Action</th>
</tr>
</thead>
<tbody id="mainBody">
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td>
Expected Total:<span id="total">0</span><br>
Added Total:<span id="totalAdd">0</span>
</td>
<td></td>
</tr>
</tfoot>
</table>
<button type="button" class="add-new btn btn-info" id="add-new">Add New Income</button>
<script id="hidden-template" type="text/x-custom-template">
<tr id="mainRow">
<td>${sno}</td>
<td>
<select name="selectProduct" id="productOption" class="form-control" selected="${optionVal}">
<option value="0"> -- Select One --</option>
<option value="1"> IPhone </option>
<option value="2"> MAC </option>
<option value="3"> Windows </option>
</select>
</td>
<td>
<input id="number_only" pattern="[0-9]" type="text" class="form-control" />
</td>
<td><!-- glyphicon-plus | glyphicon-remove -->
<button type="button" class="add-new btn btn-info glyphicon glyphicon-plus"></button>
</td>
</tr>
</script>
</body>
Stackoverflow snippet - using javascript onclick function remove current row is working fine.
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
as part of jsfiddle - test and plane html file the code is not working at-least with javascript.
Unable to delete|call delete row function. while deleting row remove the price from the Added Total.
I should only allow number for the input tag, but it is working only for the first row input element. Input type must be text only. type number allows these like {.+-}
Iam unable to solve it as new to jquery and its xpath element navigation.
There are two issues with your code:
$('table#productTable:.remove-row').on('click', function () {
here :. is an syntax error, and it is showing in console.
Second to put an event listener on dynamic html, you have to use $(document).on() like:
$(document).on('click', '.remove-row', function(){
Check the updated working fiddle
here
I have added events using on click event handler as elements get added dynamically.
Have updated both events:
1. Event for remove button
$('table#productTable').on('click', '.remove-row', function() {
//$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove(); // https://stackoverflow.com/a/11553788/5081877
//$(element).parent().remove();
//});
});
2. Event for input tag
$('table#productTable').on('input propertychange',' > tbody > tr > td:nth-child(3) > input', function() {
$.each($('input[type=text]'), function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
});
Refer this fiddle
Please change $('.row).onclick like this
$('table#productTable').on('click', '.remove-row', function()
And remove this $("#productTable").each(function () {
I am trying to hide a section based on the result of a Yes/No radio button selection where yes is true and no is false. I have it to where if the user selects a button, the field is shown, but it does it for both yes or no, also if the user clicks the no, it should remain hidden(which it doesn't). Thanks for any help.
Here is the JQuery code
$(document).ready(function () {
$('input[type="radio"]').click(function () {
if ($(this).prop('#ImportPartRadio', true)) {
$('#ImportPartQuestions').show();
}
else if ($(this).prop('#ImportPartRadio', false)){
$('#ImportPartQuestions').hide();
}
});
});
Here is the div sections
#*import parts radio button*#
<div class="span-18 last" id="ImportPart">
<table class="item-display">
<tr>
<td class="label required" id="ImportPartRadio">
<div class='tooltip'>Is this an import part?<span class="tooltiptext">This information can be used to calssify the part for US Customs purposes.</span></div></td>
<td class="value" colspan="5">
Yes: #Html.RadioButtonFor(model => model.ImportPart, true)
No: #Html.RadioButtonFor(model => model.ImportPart, false)
</td>
</tr>
</table>
</div>
#*This table is for full procurement and sales procurement setup only*#
<div class="span-18 last" id="ImportPartQuestions">
<table class="item-display">
<tr>
<td class="label">If an import, what is the material and function of part?</td>
<td colspan="5" class="value">
#Html.TextAreaFor(model => model.MaterialAndFunction, new { #placeholder = "Description Here", maxLength = 300 })
#Html.ValidationMessageFor(model => model.MaterialAndFunction)
</td>
</tr>
</table>
</div>
I have been googling for hours and can't seem to find a solution the works, this is as close as any of them come to fully working.
Here is the html code rendered by the browser
$(document).ready(function() {
$('input[name="ImportPart"]').change(function() {
var radioValue = $(this).val();
var questionsDiv = $('#ImportPartQuestions');
if (radioValue == "True") {
questionsDiv.show();
} else {
questionsDiv.hide();
}
});
});
OR using .toggle( display )
$('input[name="ImportPart"]').change(function() {
$('#ImportPartQuestions').toggle(this.value === "True");
});
$(document).ready(function () {
$('#ImportPartRadio input[type="radio"]').click(function () {
if ($(this).val() === 'True') {
$('#ImportPartQuestions').show();
} else {
$('#ImportPartQuestions').hide();
}
});
});
// edited to match case with your True value, and fixed a typo.
Why not get the change event which will be more robust:
$(document).ready(function () {
$('input[type="radio"]').change(function () {
if ($(this).val()==true) {
$('#ImportPartQuestions').show();
}
else {
$('#ImportPartQuestions').hide();
}
});
});
I am having an issue I am struggling to resolve. I have two tables
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table1">
<thead>
<tr>
<th>Campaign Type</th>
<th>Deployment Date</th>
<th>Additional Information</th>
</tr>
</thead>
<tbody>
<tr class='template'>
<td>
<select class="selectType" name='typeInput[0][campType]' id="campInput">
<option value=""></option>
<option value="Main">Main</option>
<option value="Other">Standalone</option>
</select>
</td>
<td>
<input type="text" name='typeInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
<td>
<textarea name='typeInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
</tr>
</tbody>
</table>
<a id='add' class="pull-right btn btn-default">Add Row</a>
<a id='delete' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table4">
<thead>
<tr>
<th>Additional Information</th>
<th>Deployment Date</th>
</tr>
</thead>
<tbody>
<tr class='template4'>
<td>
<textarea name='amendsInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
<td>
<input type="text" name='amendsInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
</tr>
</tbody>
</table>
<a id='add4' class="pull-right btn btn-default">Add Row</a>
<a id='delete4' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
One table has 3 inputs, the other has 2. When the add button is pushed on either table, I am cloning the table row, which includes cloning a datepicker.
Things have been going fine but now I have a problem. The second table I end everything with 4 e.g. table4, template4, add4 and delete4. I then duplicated the Javascript from the preious table but added 4 to everything (I duplicated it because this table has different inputs). This resulted in the following code.
$(function() {
initJQueryPlugins();
$('#add').on('click', function() {
$last_row = $('#table1 > tbody > tr').last();
if(!hasValues($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row($('#table1'));
}
});
$('#delete').on('click', function() { delete_row($('#table1')); });
$('#add4').on('click', function() {
$last_row = $('#table4 > tbody > tr').last();
if(!hasValues4($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row4($('#table4'));
}
});
$('#delete4').on('click', function() { delete_row4($('#table4')); });
});
function add_row($table) {
var tr_id = $table.find('tr').length - 1;
var $template = $table.find('tr.template');
var $tr = $template.clone().removeClass('template').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
$(".selectType", $tr).select2({
tags: true
});
}
function hasValues($row){
$optVal = $row.find('td option:selected').text();
$inputVal = $row.find('td input').val();
$textVal = $row.find('td textarea').val();
if($optVal != "" || $inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row($table) {
var curRowIdx = $table.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function add_row4($table4) {
var tr_id = $table4.find('tr').length - 1;
var $template = $table4.find('tr.template4');
var $tr = $template.clone().removeClass('template4').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table4.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
}
function hasValues4($row4){
$inputVal = $row4.find('td input').val();
$textVal = $row4.find('td textarea').val();
if($inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row4($table4) {
var curRowIdx = $table4.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function initJQueryPlugins() {
add_row($('#table1'));
add_row4($('#table4'));
}
I have set up a working FIDDLE
The problem is this. If you start adding a few rows in the first table, this all works fine. After this, add a few rows in the second table. This seems to work fine. However, now start deleting rows in the second table. For some reason it seems to also delete rows in the first table.
So my main question is why does this happen? Additionally, is there any way I can do this without duplicating the code? The second table does not use select2.
Thanks
You are deleting this:
$("#" + (curRowIdx - 1)).remove();
This id is also available in the first table, you have to choose a more specified selector
like:
$table4.find("#" + (curRowIdx - 1)).remove();
or better: (comment from K. Bastian above)
$table4.find('tr').last().remove()
I edited your sample here:
https://jsfiddle.net/cLssk6bv/
Here I also deleted the dublicated code, only the different insert method still exist:
https://jsfiddle.net/cLssk6bv/1/
I want to check the checkbox next to each html row if the select dropdown in the same row has something selected. Here is my html code and script. Can someone please point out what's wrong?
<tr>
<td>Sohail Abbasi</td>
<td>N&S</td>
<td>1</td>
<td>2013-01-03</td>
<td>Thursday</td>
<td>09:21</td>
<td></td>
<td>
<select class="form-control" name="duty_status[3]">
<option value="" selected="selected">Select...</option>
<option value="2">Short Leave</option><option value="5">OD</option>
</select>
</td>
<td><input class="form-control" name="user_comments[3]" type="text"></td>
<td>
<input name="submit[]" type="checkbox" value="3">
</td>
</tr>
Javascript:
$('#SelectFilled').click(function($e)
{
var elements=$('select[name^=duty_status]');
var checkboxes=new Array();
for (var i=0; i<elements.length; i++) {
if(elements[i].value)
{
var parent=elements[i].parentNode.parentNode;
checkboxes[checkboxes.length]=parent.lastChild.firstChild;
}
}
for (var j=0; j<checkboxes.length; j++) {
checkboxes[j].checked=true;
}
});
You can simplfy your traversal code and make it far easier to read by using jQuery methods:
$('select[name^=duty_status]').each(function(){
if( this.value === VALUE_I_WANT ){ /* not sure where this value comes from */
$(this).closest('tr').find(':checkbox').prop('checked', true);
}
});
This code is based on the existing click handler triggering it. The goals in question are not very clear
You would have to use something like this:
$(function() {
$('td > select').on('change', function() {
var chk = $(this).closest('tr').find(':checkbox');
chk.prop('checked', this.selectedIndex !== 0 );
})
.change();
});
JSFIDDLE DEMO
Below code should works:
$('select[name^=duty_status]').on('change', function(){
if($(this).val() != ""){ //better put some value on the first option..
$(this).parents("tr").find(":checkbox").prop('checked', true);
}else{
$(this).parents("tr").find(":checkbox").prop('checked', false);
}
});