C# - Loop through HTML textarea - javascript

I am generating HTML text areas with javascript code below:
<script>
$(document).ready(function () {
var i = 1;
$('#add').click(function () {
i++;
$('#dynamic_field').append('<tr id="row' + i + '"><td><textarea runat="server" id="choice" placeholder="Enter choice text" class="form-control"></textarea></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
});
After generating text areas, i want to get values of it. I have tried to get values with the code below:
foreach (Control item in this.Controls)
{
ArrayList ary = new ArrayList();
//We just need HtmlInputCheckBox
System.Web.UI.HtmlControls.HtmlTextArea _cbx = item as System.Web.UI.HtmlControls.HtmlTextArea;
if (_cbx != null)
{
ary.Add(_cbx.Attributes["id"].ToString());
}
}
But, it can not find any values. Any help will be appreciated, thank you.

Related

Generate a multidimensional array for php post, using data attributes of inputs

I have set a code to generate dynamic tables to capture data, which will be used to send a message to the students regarding a timetable. Following generates the required user input form, so that the user can insert the data as required.
$(document).ready(function() {
var index = 1;
var tableindex = 0;
var daydd = '<select><option value="Saturday">Saturday</option><option value="Sunday">Sunday</option></select>';
$("#addRow").click(function() {
if (tableindex == 0) {
tableindex++;
$("#myTable").append("<tr data-day='" + tableindex + "'><td colspan=3>"+daydd+" " + tableindex + "</td><td><button class='dayclose' data-day='" + tableindex + "'>Close</button></td></tr>");
}
$("#myTable").append("<tr data-day='" + tableindex + "'><td>Day " + tableindex + "</td><td>row " + index + "</td><td><input type='text' data-clday='" + tableindex + "' data-subj='" + index + "' ></td><td><button class='subjclose' id='" + index + "'>Close</button></td></tr>");
index++;
});
$("#addtable").click(function() {
tableindex++;
$("#myTable").append("<tr data-day='" + tableindex + "'><td colspan=3>"+daydd+" " + tableindex + "</td><td><button class='dayclose' data-day='" + tableindex + "'>Close</button></td></tr><tr data-day='" + tableindex + "'><td>Day " + tableindex + "</td><td>row " + index + "</td><td><input type='text' data-clday='" + tableindex + "' data-subj='" + index + "' ></td><td><button class='subjclose' id='" + tableindex + "'>Close</button></td></tr>");
index++;
});
$('table').on('click', '.subjclose', function(e) {
e.preventDefault();
$(this).parents('tr').remove();
});
$('table').on('click', '.dayclose', function(e) {
e.preventDefault();
var closeday = $(this).attr("data-day");
$('tr[data-day="' + closeday + '"]').remove();
$(this).parents('tr').remove();
});
//$('.row-container[data="product_id"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="myTable">
</table>
<input type="button" id="addRow" value="add subject" />
<input type="button" id="addtable" value="add day" />
<input type="button" id="submit" value="Send Data" />
Now I am trying to capture data to be sent to a php script, so that it can send the message to a selected set of students. My message would be as follows; (consider rows 3,4,6,9 as deleted in this scenario)
Saturday Subjects
Row 1 data
Row 2 data
Sunday Subjects
Row 5 data
Row 7 data
Monday Subjects
Row 8 data
Row 10 data
I am trying to run a for each loop for this in my php script, but I do not have any idea how to achieve this with the data attributes.
How can I generate a multidimensional array to be sent to a php script using the data attributes of inputs so that it can be used to generate a foreach loop?
You can use the JQuery function like this
$.fn.onAddDefaultValue = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
data: '',
profile_main_div_id: '',
server_div_id: '',
addi_id : '',
confirm_btn_id: ''
}, options);
$(settings.data).each(function(idx,obj){
var item_id = obj.item_id;
var item_title = obj.item_title;
// server pratik - 10112017 location widget interaction
var isLocationExist = false;
$("#"+settings.server_div_id).children().each(function () {
var child_div = $(this);
var localtion_value = child_div.find("span").text();
if (localtion_value == item_title) {
//child_div.find("span").css("border", "1px solid #f16262");
isLocationExist = true;
//return false;
}else {
//child_div.find("span").css("border", "0px solid #f16262");
}
});
if (!isLocationExist) {
var input_value = item_title;
var newTextBoxDiv = $(document.createElement('div'))
.attr({"class": 'customcheckbox',"style":'margin: 0px 0px 10px;'});
var chk_id = item_id;
newTextBoxDiv.after().html('<input type="checkbox" checked name="remember" id="'+chk_id+'" value="user_profile_remember_me-no">'+
'<input type="hidden" class="server_item_id" value="'+item_id+'" />'+
'<label style="float: right;position: relative;margin-right: 10px;border: 1px solid #000000;border-radius: 0px" for="'+chk_id+'">'+
'<div class="input-label"></div>'+
'</label>'+
'<span style="padding-left: 5px;" class="my-label1">'+input_value+'</span>');
newTextBoxDiv.appendTo("#"+settings.server_div_id);
//$("#"+settings.addi_id).slideUp();
//$(this).closest('#'+settings.profile_main_div_id).removeClass("additional-field-open");
// add new item
} else {
$('#'+settings.server_div_id).children().each(function () {
var child_div_appearance = $(this);
var title_v = $(this).find("span").text();
var status_v = $(this).find("input[type='checkbox']").prop("checked");
if((item_title == title_v) && (!status_v)){
$(this).find("input[type='checkbox']").click();//attr("checked",false)
// break loop
// return false;
}
});
}
$("#"+settings.confirm_btn_id).click();
//$("#"+settings.server_div_id).addClientNote({});
});
};
and remove added element like this
$.fn.removeDiagnosisValue = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
title: ''
}, options);
$(this).children().each(function () {
var child_div = $(this);
var div_buttons = child_div.find("div");
var i = 0;
$(div_buttons).children().each(function () {
// delete icon
var child_span = $(this);
if (child_span.attr('name') == "delete") {
var img_delete = child_span.find("img");
img_delete.click(function () {
child_div.remove();
});
// break loop
return false;
}
});
});
};

How can you pull data from multiple variables from a button that opens a bootstrap modal?

The my-link2 and mylink3 aren't pulling in any data for some reason. They show undefined. So I am not sure what I am doing wrong?
Button:
<input class='btn btn-default'
data-mylink=\"$row[auditID]\"
data-mylink2=\"$audit_type\"
data-mylink3=\"$row[audit_instanceID]\"
type=button
data-toggle='modal'
data-target='#perform_audit'
value='Take Audit' />
Jquery:
$('#perform_audit').on('shown.bs.modal', function (e) {
var btn = $(e.relatedTarget);
var auditID = btn.data('mylink');
var audittype = btn.data('mylink2');
var auditinstanceID = btn.data('mylink3');
$('#editfindings_audit1').text(auditID);
$('#editfindings_audit1').text(audittype);
$('#editfindings_audit1').text(auditinstanceID);
alert(auditID + " : "+audittype+ " : " + audittype);
$('#editfindings_audit1').load("answer_audit.php?auditID="+auditID+"&audit_type="+audittype+"&action=answer&audit_instanceID="+auditinstanceID);
//answer_audit.php?auditID=214&action=answer&audit_instanceID=572
//alert(auditID +" 0"+ audittype +" 0" +auditinstanceID);
//window.open("answer_audit.php?auditID="+auditID+"&audit_type="+audittype+"&action=answer&audit_instanceID="+auditinstanceID)
});//End [Take Audit] button
I think you should use .attr() instead of .data(). Try this:
$('#perform_audit').on('shown.bs.modal', function (e) {
var btn = $(e.relatedTarget);
var auditID = btn.attr('data-mylink');
var audittype = btn.attr('data-mylink2');
var auditinstanceID = btn.attr('data-mylink3');
$('#editfindings_audit1').text(auditID);
$('#editfindings_audit1').text(audittype);
$('#editfindings_audit1').text(auditinstanceID);
alert(auditID + " : "+audittype+ " : " + audittype);
$('#editfindings_audit1').load("answer_audit.php?auditID="+auditID+"&audit_type="+audittype+"&action=answer&audit_instanceID="+auditinstanceID);
//answer_audit.php?auditID=214&action=answer&audit_instanceID=572
//alert(auditID +" 0"+ audittype +" 0" +auditinstanceID);
//window.open("answer_audit.php?auditID="+auditID+"&audit_type="+audittype+"&action=answer&audit_instanceID="+auditinstanceID)
});//End [Take Audit] button

Cannot select a button which appended dynamically in jQuery

I use getJSON function in jQuery and append the retrieved result in the form of button in the DOM. however I cannot use the selector on the appended DOM.
here is my script:
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
})
this is what i use to select:
$(':button.diaries').click(function(){});
but it seems not working. however when I put a dummy button with the same class in the HTML body, it is selected perfectly. Can you guys give me any suggestion?
#Kelvin Aliyanto ....So the solution will be like this
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
});
$('div').on('click', '.diaries', function(event){
alert("Hi");
}) ;
});
</script>
<div id="diaryList"></div>
check your code is after document ready
$(document).ready(function(){ //your code here });
and use
$('button.diaries').on(click , function(){})
instead of .click

How to get the values of all textfields in add/remove textfields and form JSON

I'm using a plugin to duplicate textfields on add and remove buttons. Now, after getting the fields added and removed, I want to form JSON out of all the textfields and POST it on submit.
Below is the code -
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
JSFiddle can be referred to.
I want to get the values of all textfields and form JSON.
Iterate through the input fields, grab their values, and push them through JSON.stringify to create your desired JSON.
function serializeAndPost() {
var values = [];
$( '#p_scents input[id^=p_scnt_]' ).each( function ( index, element ) {
values.push( element.value );
} );
var json = JSON.stringify( { "welcomesList": values } );
// Do your POSTing here
}
Updated fiddle:
https://jsfiddle.net/tZPg4/11019/
I don't know if this is the best solution as I am building a string rather than an JSON object but here is my solution:
HTML
<input type="button" id="btnSubmit" value="Submit"></input>
JS:
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('#btnSubmit').click(function(e) {
e.preventDefault();
var str = [];
$.each($('input[type=text]'), function(i, val) {
var el = $(this);
str.push('"' + el.attr("id") + '":"' + el.val() +'"');
});
var json_string = "{" + str + "}";
});
});

Build a array of div's id using each DIV inside section

I'm trying to get the ID of each DIV inside this HTML code
<section id="choices">
<div id="talla_choice_24" style="">
...
</div>
<div id="color_choice_25" style="">
...
</div>
<div id="sport_choice_26" style="">
...
</div>
<button type="button" class="create-variation" id="create-variation" style="">Crear variaciones</button>
<section id="variations_holder" style="display: none"></section>
</section>
So I made this:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($(this).val());
})
return inputValues;
}
And I call here:
$('#choices').on("click", "#create-variation", function(e) {
var parent_id = $(this).closest("section").attr("id");
var element = getDivId(parent_id);
iterateChoices("", element[0], element.slice(1), 0);
});
I need to build something like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#sport_choice_26 input:text'));
But I get this error:
Uncaught TypeError: Object has no method 'each'
What is wrong?
UPDATE
This is the code for iterateChoices() function:
function iterateChoices(row, element, choices, counter) {
if ($.isArray(choices) && choices.length > 0) {
element.each(function(index, item) {
if (counter == 0)
row = '<input type="text" required="required" value="" name="pupc[]" /><input type="text" required="required" value="" name="pprice[]" /><input type="text" required="required" value="" name="pqty[]" />';
iterateChoices(row + '<input value="' + item.value + '">', choices[0], choices.slice(1), counter + 1);
});
} else {
html_temp = "";
$.each(element, function(index, item) {
html_temp += row + '<input value="' + item.value + '"><br>';
});
html += html_temp;
}
}
I also made some changes at this code:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push("#" + $(this).attr('id') + ' input:text');
});
return inputValues;
}
And now the error change to this:
Uncaught TypeError: Object #talla_choice_24 input:text has no method 'each'
UPDATE 2
I still continue change getDivId() function to build a array like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#number_choice_23 input:text'), $('#sport_choice_23 input:text'));
But can't get it since array values are constructed as strings, see below:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push('$("#' + $(this).attr('id') + ' input:text")');
});
return inputValues;
}
I'm getting:
("$('#talla_choice_24 input:text')", "$('#color_choice_25 input:text')")
I think there is the problem
You are using the val method on a div element, which just returns an empty string. There is no each method on a string.
You don't need the id of each div to get the input elements inside them. This will get you the inputs in a single jQuery object:
var element = $(this).closest("section").find("> div input:text");
If you really need an array of separate jQuery objects, you can then do this:
element = element.map(function(){ return $(this); }).get();
var arr = [];
$("#create-variation").on('click', function(){
$("#choices > div").each(function(a,b){
arr.push($(this).text());
});
});
After some headaches I realized how to fix the (my) error, here is the solution to all the problems:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($("#" + $(this).attr('id') + " input:text"));
});
return inputValues;
}

Categories

Resources