I am having problem to append <option> in <select> as my scenario is I am showing all list if users want to add their own option so I am opening model and take input from user
And problem is I am not able append user input with their specify Select option
as I have add more options to
HTML:
<li style="width: 27%;">
<label class="select">
<span style="display: inline-block;padding: 10px 0;">Institute:</span>
<select name="institute[]" id="institue1" onchange="Myinsi(this.value, 'institue1')" class="validate[required] institute" style="width: 65%;float: right;">
<option value="">Select</option>
<?php
$sel = "select * from institute where `status`= 'Y'";
$res = mysql_query($sel);
while ($row = mysql_fetch_assoc($res)) {
echo "<option value='{$row['title']}'>{$row['title']}</option>\n";
}
echo'<option value="ShowOtherIns" id="ShowOtherIns">Other</option>';
?>
</select>
<i></i>
</label>
</li>
jQuery Code:
<script>
function Myinsi(value, id) {
console.log(value + '----' + id);
var index = $(id + ' option').length + 1;
if (value == "ShowOtherIns") {
$('#OtherIns').modal("show");
document.getElementById("btnSave").onclick = function () {
var NewText = document.getElementById('OtherInsTextID').value;
if (NewText = !'') {
var element = document.getElementById(id); // assuming ul exists
$(id).append('<option value="' + NewText + '" selected="selected">' + NewText + '</option>');
$('#OtherIns').modal("hide");
} else {
console.log("text = exibir menu");
}
};
}
}
</script>
I am attaching my screen shoot too
Jquery selector is incorrect. You have to write "#" followed by the id of your html element. In the line var index = $(id + ' option').length + 1; you should write var index = $('#'+id + ' option').length + 1;.
Also in the line $(id).append('<option value="' + NewText + '" selected="selected">' + NewText + '</option>'); you should write $('#'+id).append('<option value="' + NewText + '" selected="selected">' + NewText + '</option>');
Related
I want to get the value of an data-* attribute from a dynamically created select in a table when I change an option. I am getting an "Uncaught ReferenceError: index is not defined".
The creating HTML is:
html += "<td style='width : 1%; white-space: nowrap;'><select name='parRating'>"
for (let i = 0; i <= paraArray; i++) {
html += "<option name='parRatingOption' data-index='" + i + "' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>"
};
html += "</select></td>";
The option change catch is:
$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
e.preventDefault();
alert("this.value: " + this.value);//works
alert("this.data-index: " + this.data-index);//Uncaught ReferenceError: index is not defined
});
I have also tried:
alert("this.attr('data-index'): " + $(this).attr("data-index")); //undefined
You need to make sure to target the data-attribute correctly,
the value of the option gets returned from the parent selector (select), but the option itself needs to be accessed differently.
Use dataset to target data attributes.
let paraArray = ['one','two','three'];
let parIdArray = ['idOne','idTwo','idThree'];
let parRatingArray = [1,2,3];
let html = '';
html += "<td><select name='parRating'>";
for (let i = 0; i < paraArray.length; i++) {
html += "<option name='parRatingOption' data-index='" + i + "' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>";
}
html += "</select></td>";
$('#showPatientPARForm table').append(html);
$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
e.preventDefault();
alert("this.value: " + this.value);//works
// select the data attribute correctly:
//alert(this.options[this.options.selectedIndex].dataset.index);
alert(this.options.selectedIndex)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showPatientPARForm">
<table></table>
</div>
what is the way when add new row in table to make script connect with element in new row not only at first row? the script connect only with element "textbox" in the first row only
function GetSelectedvalues (el) {
var select = document.getElementsByClassName ('js-example-basic-multiple')[0];
var result = "";
var options = select && select.options;
var opt;
for (var i = 0; i < select.options.length; i++) {
opt = options[i];
var isSelected = select.options[i].selected;
isSelected = (isSelected)? opt.value : "0";
result += isSelected ;
}
document.getElementById ('textbox').value=result;
}
//add row
function addmaintable() {
$('#datatablereqstsched').append(
'<tbody>' +
'<tr class="parent" id="parent">' +
// here text box
'<td width="60%"><div class="input-group"> <label class="ckbox mg-t-10" title="Daily" ><input type="checkbox" id="chk1" onclick="check(\'chk1\')" ><span calss="mg-t-0">Daily</span> </label><div class="input-group-prepend" style="width:80%"><select class="js-example-basic-multiple col-md-4 form-control" name="states[]" multiple="multiple"style="width: 100%" onchange="GetSelectedvalues(event);" > <option value="1">MON</option> <option value="2">TUE</option> <option value="3">WED</option> <option value="4">THU</option><option value="5">FRI</option><option value="6">SAT</option><option value="7">SUN</option> </select></div><input type="text" class="form-control txtv" value="" placeholder="0000000" id="textbox" disabled></div> </td>' +
'</tr>' +
'</tbody>');
$('.js-example-basic-multiple').select2();
}
function check(chk) {
var checkb = document.getElementById(chk);
if (checkb.checked == true) {
document.getElementById('textbox').value = "1234567";
$(".js-example-basic-multiple").prop("disabled", true);
}
else {
document.getElementById('textbox').value = "0000000";
$(".js-example-basic-multiple").prop("disabled", false);
$(".js-example-basic-multiple").val(null).trigger('change');
}
}
You are explicitly targetting the first select each time you call the GetSelectedvalues function:
var select = document.getElementsByClassName ('js-example-basic-multiple')[0];
I think you should rather leverage the event argument to get the current changing select:
const tBody = '<tbody>'
+ '<tr class="parent" id="parent">'
+ '<td width="60%">'
+ '<div class="input-group">'
+ '<label class="ckbox mg-t-10" title="Daily">'
+ '<input type="checkbox" id="chk1" onclick="check(\chk1\)" >'
+ '<span calss="mg-t-0">Daily</span>'
+ '</label>'
+ '<div class="input-group-prepend" style="width:80%">'
+ '<select class="js-example-basic-multiple col-md-4 form-control" name="states[]" multiple="multiple" style="width: 100%" onchange="GetSelectedvalues(event);">'
+ '<option value="1">MON</option>'
+ '<option value="2">TUE</option>'
+ '<option value="3">WED</option>'
+ '<option value="4">THU</option>'
+ '<option value="5">FRI</option>'
+ '<option value="6">SAT</option>'
+ '<option value="7">SUN</option>'
+ '</select>'
+ '</div>'
+ '<input type="text" class="form-control txtv" value="" placeholder="0000000" id="textbox" disabled>'
+ '</div>'
+ '</td>'
+ '</tr>'
+'</tbody>'
function GetSelectedvalues(event) {
// Here you are selecting only the first select with the class "js-example-basic-multiple"
var select = document.getElementsByClassName('js-example-basic-multiple')[0];
// You are better off selecting the current changing select using the argument event
select = event.target;
var result = "";
var options = select && select.options;
var opt;
for (var i = 0; i < select.options.length; i++) {
opt = options[i];
var isSelected = select.options[i].selected;
isSelected = (isSelected) ? opt.value : "0";
result += isSelected;
}
document.getElementById('textbox').value = result;
}
//add row
function addmaintable() {
$('#datatablereqstsched').append(tBody);
$('.js-example-basic-multiple').select2();
}
Edit
Now you need a way to know which textbox to update, based on currently changing select. And the same thing for all other inputs, like the checkbox at the top.
One way to do that could be this:
const tBodyTemplate = '<tbody>'
+ '<tr class="parent" id="parent">'
+ '<td width="60%">'
+ '<div class="input-group">'
+ '<label class="ckbox mg-t-10" title="Daily">'
+ '<input type="checkbox" id="chk" onclick="check(chk)" >'
+ '<span calss="mg-t-0">Daily</span>'
+ '</label>'
+ '<div class="input-group-prepend" style="width:80%">'
+ '<select data-target="textbox" class="js-example-basic-multiple col-md-4 form-control" name="states[]" multiple="multiple" style="width: 100%" onchange="GetSelectedvalues(event);">'
+ '<option value="1">MON</option>'
+ '<option value="2">TUE</option>'
+ '<option value="3">WED</option>'
+ '<option value="4">THU</option>'
+ '<option value="5">FRI</option>'
+ '<option value="6">SAT</option>'
+ '<option value="7">SUN</option>'
+ '</select>'
+ '</div>'
+ '<input type="text" class="form-control txtv" value="" placeholder="0000000" id="textbox" disabled>'
+ '</div>'
+ '</td>'
+ '</tr>'
+'</tbody>'
function GetSelectedvalues(event) {
// Here you are selecting only the first select with the class "js-example-basic-multiple"
var select = document.getElementsByClassName('js-example-basic-multiple')[0];
// You are better off selecting the current changing select using the argument event
select = event.target;
var textboxId = select.dataset.target;
var result = "";
var options = select && select.options;
var opt;
for (var i = 0; i < select.options.length; i++) {
opt = options[i];
var isSelected = select.options[i].selected;
isSelected = (isSelected) ? opt.value : "0";
result += isSelected;
}
document.getElementById(textboxId).value = result;
}
let rowCount = 0;
//add row
function addmaintable() {
rowCount++;
var tBody = tBodyTemplate
.replace(/textbox/g, 'textbox' + rowCount)
.replace(/chk/g, 'chk' + rowCount);
$('#datatablereqstsched').append(tBody);
}
function check(v) {
console.log(v);
}
$('#add-row').click(addmaintable);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="datatablereqstsched"></table>
<button id="add-row">Add one row</button>
I receive an array from the controller which I put into the table and generate links to "edit", "delete", and "merge". The "edit" event passes variable to function which opens dialog where variable lSynonyms should be presented as multiline similarly to Synonyms shown in the table. I tried:
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '\r\n';
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '\n';
Both give me error "Unterminated string constant" when I click "edit" link. If I remove \r\n the function is working good except data in textarea is not appeared as new lines. How to pass these new line correctly?
Code which generates table
for (i = 0; i < data.length; i++) {
var Synonyms = '';
var lSynonyms = '';
for (j = 0; j < data[i]['varNames'].length; j++) {
Synonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '<br/>';
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + "\r\n";
}
$("#teamstable > tbody").append('<tr><td>' + data[i]["stdTeamID"] + '</td><td>' + data[i]["stdName"] + '</td><td>' + Synonyms + '</td><td><a onclick="updateform(' + data[i]["stdTeamID"] + ',\'' + data[i]["stdName"] + '\',\'' + lSynonyms + '\')">edit</a>' + ' <a onclick="mergeform(' + data[i]["stdTeamID"] + ')">merge</a> ' + '<a onclick="RemoveTeam(' + data[i]["stdTeamID"] + ')">delete</a></td></tr>');
}
Function to open dialog:
function updateform(id, rTeam, sTeam) {
$('#id').val(id);
$('#iID').val(id);
$('#sTeam').val(rTeam);
$('#vTeam').val(sTeam);
updatedialog.dialog("open");
}
The dialog which is opening:
<div id="dialog-form" title="Update Dialog">
<form>
<fieldset>
<label for="iID">Match ID</label>
<input type="text" name="iID" id="iID" value="" class="text ui-widget-content ui-corner-all" />
<label for="rTeam">Standardized Name</label>
<input type="text" name="sTeam" id="sTeam" value="" class="text ui-widget-content ui-corner-all">
<label for="sTeam">ID > Known Synonyms</label>
<textarea rows="6" id="vTeam" class="form-control" style="min-width: 100%"></textarea>
<input type="hidden" name="id" id="id" value="" />
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
So, the idea here is that the data variable is available in context. It might be a bit more of a hassle if you don't have it available.
But the idea is that you just need a pointer back to the data, and you can get it later. And you can put the pointer in the HTML in a data- property.
So here, the HTML construction is the same, except that instead of calling updateform from the HTML, you just tell it "use index 0" or whatever. I also added a class onto the links to make them easier to identify when attaching the event handlers.
From that piece of information, you can create the necessary arguments to updateform and call it.
$(function() {
function updateform(id, rTeam, sTeam) {
/* same as before */
console.log(id, rTeam, sTeam);
}
var data = [{
stdTeamID: 912,
stdName: "912",
varNames: [{
varTeamID: 913,
varName: "913"
},
{
varTeamID: 914,
varName: "914"
}
]
}];
for (var i = 0; i < data.length; i++) {
var Synonyms = "";
for (j = 0; j < data[i]['varNames'].length; j++) {
Synonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '<br/>';
}
$("#teamstable > tbody").append('<tr><td>' + data[i]["stdTeamID"] + '</td><td>' + data[i]["stdName"] + '</td><td>' + Synonyms + '</td><td><a class="updateform" data-index="' + i + '"">edit</a>' + ' <a onclick="mergeform(' + data[i]["stdTeamID"] + ')">merge</a> ' + '<a onclick="RemoveTeam(' + data[i]["stdTeamID"] + ')">delete</a></td></tr>');
}
$('#teamstable').on('click', '.updateform', function(e) {
var i = parseInt($(this).attr('data-index'), 10);
var teamId = data[i]["stdTeamID"];
var teamName = data[i]["stdName"];
var lSynonyms = "";
for (var j = 0; j < data[i]['varNames'].length; j++) {
lSynonyms += data[i]['varNames'][j]['varTeamID'] + ' > ' + data[i]['varNames'][j]['varName'] + '\r\n';
}
updateform(teamId, teamName, lSynonyms);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="teamstable">
<tbody>
</tbody>
</table>
I have 2 dropdownlist that will fire an event if both of them are changed.
(meaning, any changes on the indices will fire a json request that is based on the dropdownlist's current value and append them to my table).
My question is that,as soon as the page loaded, are there any ways to pre-select their indices and fire the event at the same time? I am planning to set them based on the current term and school year.
Here is my jquery code:
$schoolyear = $('select#schoolyear');
$schoolterm = $('select#schoolterm')
$tbl = $('#classview');
$schoolyear.change(function () {
getCL();
});
$schoolterm.change(function () {
getCL();
});
function getCL() {
$.getJSON('#Url.Action("getClassList","Enrollment")', { term: $schoolterm.val(), year: $schoolyear.val() }, function (e) {
$tbl.find('tbody').remove();
if (e.length > 0) {
$(e).each(function (index, e) {
$tbl.append('<tr><td>' + e.subj + '</td><td>' + e.days + '</td><td>' + e.cstart + '</td><td>' + e.cend + '</td><td>' + e.professor + '</td><td>' + e.units + '</td><td>' + e.status +
'</td>' + '<td>' + '<form action="/Enrollment/dropClass" method="post">' + '<input type="hidden" name="test" value="'+e.id+'"/>' +
' Delete ' + '</form></td></tr>')
});
}
else {
$tbl.append('<tr><td colspan="8">No match found</td></tr>');
}
//compute t
});
}
Can trigger the change on one of them while setting value
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var term = Math.ceil(month/4);// needs verification on how term is set
$schoolyear
.change(getCL)
.val(year);//set year value
$schoolterm
.change(getCL)
// trigger change after setting value, will call getCL()
.val(term).change();
Try just adding getCL() at the bottom of your script.
$schoolyear = $('select#schoolyear');
$schoolterm = $('select#schoolterm')
$tbl = $('#classview');
$schoolyear.change(function () {
getCL();
});
$schoolterm.change(function () {
getCL();
});
function getCL() {
$.getJSON('#Url.Action("getClassList","Enrollment")', { term: $schoolterm.val(), year: $schoolyear.val() }, function (e) {
$tbl.find('tbody').remove();
if (e.length > 0) {
$(e).each(function (index, e) {
$tbl.append('<tr><td>' + e.subj + '</td><td>' + e.days + '</td><td>' + e.cstart + '</td><td>' + e.cend + '</td><td>' + e.professor + '</td><td>' + e.units + '</td><td>' + e.status +
'</td>' + '<td>' + '<form action="/Enrollment/dropClass" method="post">' + '<input type="hidden" name="test" value="'+e.id+'"/>' +
' Delete ' + '</form></td></tr>')
});
}
else {
$tbl.append('<tr><td colspan="8">No match found</td></tr>');
}
//compute t
});
}
getCL(); //this will run once when page is loaded.
To answer your other question, you can set a default pre-selected option in the dropdown by adding selected to your dropdown. For example:
<select>
<option value="2012">2012</option>
<option value="2013" selected>2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>
I'm trying to show div#options_holder and create some elements inside it by using this code:
var counter = 1;
$('#choices').on("change", ":checkbox", function(e) {
var theName = $(this).attr('name');
var theID = $(this).attr('id');
var isChecked = $(this).prop("checked");
var input, button, append = "";
$("#options_holder").show();
input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';
append = counter === 1 ? input += button : input;
$("#options_holder").append(append);
counter++;
console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});
But it does not work since div#options_holder remains hidden and elements aren't created, is something wrong? It's supposed that those should happen any time I mark a checkbox, if I unmark in the other hand the process should be reverted meanind div#options_holder will be hidden and any element inside it should be destroyed, what's wrong?
Making sure that your selectors work and your IDs are correct are often easily overlooked. Glad we could help you find your typing mistake :-)
Working code fiddle: http://jsfiddle.net/pXJpr/
HTML:
<div id="choices">
<input type="checkbox" name="testName" id="testId" />
</div>
<div id="options_holder" style="display:none;">
</div>
JS:
var counter = 1;
$('#choices').on("change", ":checkbox", function(e) {
var theName = $(this).attr('name');
var theID = $(this).attr('id');
var isChecked = $(this).prop("checked");
var input, button, append = "";
$("#options_holder").show();
input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';
append = counter === 1 ? input += button : input;
$("#options_holder").append(append);
counter++;
console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});
function capitalize(s) {
return s;
}