I am using Aspnet, and i need to create an undetermined number of labels for one specific page.
I have a button that calls a function which generates a label dynamically using javascript:
<script type="text/javascript">
function create() {
var newlabel = document.createElement("box1");
...
document.getElementById("MainContent_revenuestreams").appendChild(newlabel);
}
</script>
What happens is that after the label is created he only shows on the webpage for about 2-3 seconds and after that it disapears (i think that the postback eliminates its content).
I would like to know how can i avoid this
document.createElement(type) - type must be a html tag name like: div, table, p.
In your case:
var newLabel = document.createElement("label");
Then you set attributes for this element (for - most important in label, id, name).
Finally:
newLabel.appendChild(document.createTextNode("This is where label caption should be"));
document.getElementById("MainContent_revenuestreams").appendChild(newLabel);
Some links:
http://www.w3schools.com/jsref/met_document_createelement.asp
http://www.w3schools.com/jsref/met_document_createtextnode.asp
As you see box1 is not a valid argument for document.createElement(type).
You have to return false to cancel the postback of the button:
<asp:Button runat="server" OnClientClick="javascript: create();return false;"/>
Also note that document.createElement("box1"); will create a <box1></box1> element which is probably not what you want. You should change "box1" to "label" or "span"
Add OnClientClick="addNewlabel();return false;"
function addNewlabel() {
var NumOfRow++;
var mainDiv=document.getElementById('MainDiv');
var newDiv=document.createElement('div');
newDiv.setAttribute('id','innerDiv'+NumOfRow);
var newSpan=document.createElement('span');
newSpan.innerHTML="Your Label Name";
// append the span
newDiv.appendChild(newSpan);
mainDiv.appendChild(newDiv);
}
Related
Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
var mouse_down = false;
var row, col; // starting row and column
var $tr;
$("#tblPersonale td")
.mousedown(function () {
$("#col_to").html('?');
mouse_down = true;
// clear last selection for a fresh start
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
$tr = $(this).parent();
row = $tr.parent().find("tr").index($(this).parent());
col = $tr.find("td").index($(this));
$("#row").html(row);
$("#col_fr").html(col - 1);
return false; // prevent text selection
})
.mouseover(function () {
if (mouse_down) {
$("#col_to").html('?');
if ($tr[0] === $(this).parent()[0]) {
var col2 = $(this).parent().find("td").index($(this)); // current column
var col1 = col;
if (col > col2) { col1 = col2; col2 = col; }
$("#col_fr").html(col1-1);
$("#col_to").html(col2 - 1);
// clear all selection to avoid extra cells selected
$(".highlighted").removeClass("highlighted");
// then select cells from col to col2
for (var i = col1; i <= col2; i++) {
if (col1>1){
$tr[0].cells[i].className = "highlighted";}
}
}
}
})
.bind("selectstart", function () {
return false; // prevent text selction in IE
})
$(document)
.mouseup(function () {
mouse_down = false;
});
});
So, when user selects one or more cells I have the start/end value in here:
<span id="col_fr" runat="server" enableviewstate="true">?</span>
<span id="col_to" runat="server" enableviewstate="true">?</span>
Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click">
The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true" />
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">
Thanks
It just have to move the parameter code o a javascript function like
function getURL(){
var param1 = someField.value/*get field value*/;
var url= "Home.aspx?col_fr="+ param1;
window.location= url;
return false;
}
Html
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="getURL()">
Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO
include jquery in your page
Download and include css and js for colorbox
In your page add a html tag with on click event
Add a script section in your page
function openLink()
{
var hiddenValue= $("#col_fr").text(); // or .html()
var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
$.colorbox({
iframe: true,
width: "75%",
height: "75%",
href: urlToOpen
});
}
Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!
Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
document.getElementById("hdncol_fr").value = col - 1;
document.getElementById("hdncol_to").value = col2 - 1;
document.getElementById("hdnrow").value = row;
}
This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.
I tried to enable a disabled element on click of a P element.The code below will store the value from the textbox into another textbox which I have appended with the div.later this textbox will be disabled.On mouse over the div an edit and delete will appear.On click of the edit, the textbox within the div must be enabled again.
<div id="ta"></div>
<input type="text" id="tb"><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var ta="";
function add() {
var newDiv="",newTa="",newP="",newImg="";
ta=document.getElementById('ta');
newDiv = document.createElement("div");
ta.appendChild(newDiv);
newTa = document.createElement("input");
newTa.type="text"
newTa.disabled="true";
newTa.value=document.getElementById("tb").value;
newDiv.onmousedown=function(){
newP.style.visibility="visible";
newImg.style.visibility="visible";
};
newP=document.createElement("p");
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.style.padding="5px";
newP.onclick=function()
{
newTa.disabled="false";//this is not working
}
Why is it not working?Is there any other way to do this?
The reason is probably because you are providing "false" as a string. From another answer here:
[...] a non empty string is truthy. So assigning "false" to the disabled property has the same effect of setting it to true.
Try using the proper boolean value instead.
newTa.disabled = false;
newTa.disabled="true"
newTa.disabled="false"
these two should be without ""
newTa.disabled=true
newTa.disabled=false
otherwise you could do it like this:
var x = document.getElementById("mySelect").disabled;
https://www.w3schools.com/jsref/prop_select_disabled.asp
Fiddle
I am trying to clone a span from the onClick() function of a button. First time this works fine but when I try second time it is not cloning. What am I doing wrong?
Here is the essence of my code.
$(document).ready(function(){
$('.addmachinerow').on('click',function(){
var edcname = $('.edc_name option:selected').val();
var machine_description = $("input[name='machine_description'").val();
var capacity = $("input[name='capacity'").val();
var voltage_level = $("input[name='voltage_level'").val();
var powertype = $("select[name='typeofpower'").val();
var edcautovalue = $('.ecaddingspan').attr('data-value');
//if($('#bank_increment').html() == '') $('#bank_increment').html('0'); else $('#bank_increment').html(parseInt($('#bank_increment').html())+1);
//if($('#bank_clickededit').html() == '') var bank_increment = $('#bank_increment').html(); else var bank_increment = $('#bank_clickededit').html();
$('.ecaddingspan').clone().appendTo('.edcparent');
//$('.bankname, .bankbranch , .IFSCcode , .bankaccno , .accsincefrom').val('');
var edc_details = {'edcname' : edcname, 'machine_description' : machine_description, 'capacity' : capacity, 'voltage_level' : voltage_level, 'powertype' : powertype }
//$('.bank_details_array').append(JSON.stringify(bank_details)+'&&');
});
});
Additionally:
How can i clone the entire sets on clicking the Total clone button ?
I need to save the values in array with different names. Is that possible ?
How can i clone the entire sets on clicking the Total clone button ?
You've to use event delagtion on() instead :
$('body').on('click','.addmachinerow', function(){
//Event code
})
Since the new .addmachinerow added to the page dynamically after the clone.
I need to save the values in array with different names is that possible ?
I suggest the use of the array name [] like :
<input name='machine_description[]' />
<input name='voltage_level[]' />
Hope this helps.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('.cloneitem').not('.cloned').clone().addClass('cloned').appendTo('body');
});
});
</script>
</head>
<body>
<p class="cloneitem">This is a paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
</html>
The issue is a common misconception of JQuery selectors. If you play with ID selectors then switch to class selectors then you often don't notice a difference in behaviour. The ID selector doc says
ID Selector: If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM
whilst for the class selector
Class Selector: Selects all elements with the given class.
What this means is that when you clone the target element you get away with a subsequent ID selection (JQuery ignores the duplicates) but a subsequent class selection will trip you up if you were not expecting JQuery to return multiple matches. Class selectors are great for grouping elements but not so great for cloning.
While I am on the soap box - whenever you use the clone function you should consider and fix the potential duplicate ID and un-required class duplicates that you are producing. Duplicate ID's are definitely bad show - duplicate classes may actually be by design but you should still consider them.
In the code sample below I assign the class iAmSpartacus to the original span which the onClick() function then clones. Each clone also gets the iAmSpartacus class so I remove it from each new clone to ensure that the $(".iAmSpartacus") selector always returns a maximum of one element. The spans show their current class property to prove the point.
// this runs one - shows us classes of original span
var origSpan=$(".iAmSpartacus")
origSpan.html("My classes are: " + origSpan.prop("class"))
$("#daButton").on("click", function(e) {
var newSpan = $(".iAmSpartacus").clone();
newSpan.removeClass("iAmSpartacus"); // remove the dup targetting class
newSpan.appendTo('.edcparent');
newSpan.html("My classes are: " + newSpan.prop("class"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="daButton">Click me</button>
<div class="edcparent" style="border: 1px solid red;">
<span class="ecaddingspan iAmSpartacus" style="display: block;">I am a span</span>
</div>
I create a textarea and a button on a loop based on a certain condition:
while($row_c= mysqli_fetch_array($result_comments))
{
//some code goes here
<textarea type="text" id="pm_text" name="text"></textarea><br>
<button name="send_comment" id="post_comment" class="button" onClick="post_pm_comment()">Post</button>
}
Now in my function "post_pm_comment" I would like to access the text written in the textarea when the post button is clicked.
I tried this, but it only gives me the text of the first textarea and button created:
function post_pm_comment(thidid, pm_id, path, pm,getter)
{
var pm_text = document.getElementById("pm_text").value;
}
What should I do?
Thank you
Your code is outputting an invalid DOM structure, because id values must be unique on the page. You cannot have the same id on more than one element. Remove the id values entirely, you don't need them.
Having done that, the minimal-changes answer is to pass this into your handler:
onClick="post_pm_comment(this)"
...and then in your handler, do the navigation:
function post_pm_comment(postButton)
{
var pm_text;
var textarea = postButton.previousSibling;
while (textarea && textarea.nodeName.toUpperCase() !== "TEXTAREA") {
textarea = textarea.previousSibling;
}
if (textarea) {
pm_text = textarea.value; // Or you may want .innerHTML instead
// Do something with it
}
}
Live Example | Source
I have a code which allows me to add certain "absentees", along with their ID's through a hidden form, to the absentees list when I click on them. When I click on it again, the "absentee" is removed from the absentees list. However, when I click on it again, the list seems to extend further because of a br
in my code plus the hidden form value doesn't seem to be removed. I need the hidden value removed so that the removed absentee from the list will not be recorded in the database. I need the br
so that the absentee listing will be presentable.
Here's my code: http://jsfiddle.net/gk5pV/8/
I wholeheartedly agree with #charlietfl, just use a block level element. Also, use a single hidden input to track your absentees. Example fiddle, code below:
$(function() {
$("td").click(function() {
var $this = $(this);
var user = $this.attr('id');
var p = $('<p />').attr('user', user).text($this.text());
var absentees = [];
if ($('#absentees').val().length > 0) {
absentees = $('#absentees').val().split(',')
}
if ($(this).hasClass('on')) {
//console.log("Already marked absent");
//remove from collection
$("#collect").children('p[user="' + user + '"]').remove();
absentees.splice(absentees.indexOf(user), 1);
}
else {
//console.log(user);
//add to collection
$("#collect").append(p);
absentees.push(user);
}
$this.toggleClass('on');
$('#absentees').val(absentees.join(','));
});
$("#clicky").click(function() {
$('td').removeClass('on');
$("#collect").empty();
$('#absentees').val('');
});
});
Solution is fairly simple. Wrap the text you want to append and hidden input in a block level element ( div, p, li etc) and you won't need a <br tag. WHen you remove the absentee from list you remove the block element and the input will be part of it so it will no longer exist. If you give the new block level element a class name you can simply attach your event handler to the class