Code first:
function loopForm() {
var e = document.getElementById("form1").elements;
for (var i = 0; i < e.length; i++) {
alert('this is ' + e[i].ID + ' of type' + e[i].type);
}
I have the above code sitting in a .js, which is called from a .aspx with dynamic created controls like textbox, dropdownlist, checkbox and labels, in Server side, in a form called form1. My question is,
the code is picking up all the controls' ID and types, except
labels and I am looking for a way to manipulate with label (change
style.display, color, etc)
I have attempted with JQuery code such as:
$("#form1 label").each(function() { //I used "div", "label" and all sort
alert('hi');
});
and does not work. Please note that while document.getElementById might work, the controls exist on the page differ from everytime so it cannot be hardcoded.
EDIT: Here's how label is added to the .aspx (in my codebehind):
private Label lbl = new Label();
System.Web.UI.HtmlControls.HtmlGenericControl NewDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
NewDiv1.Controls.Add(lbl);
form1.Controls.Add(NewDiv);
When you talk about labels, I suspect you are referring to ASP.NET server controls, such as asp:Label. If that is the case, then you're really looking for <span> tags, as ASP.NET turns a <asp:Label> into an html <span>.
And if you want to refer to these elements by their Id, you will notice that ASP.NET does not use the same Id on the client side as what you defined on the server side.
However, there is a workaround. If you want the client Id to be the same as the server id, set the following property on your server control: ClientIdMode="Static".
For example, in your .aspx page you have this:
<asp:Label runat="server" Id="lblName"></asp:Label>
It will generate something like this in the html:
<span id="someservergeneratedid_lblName"></span>
If you want to control the id yourself, you can do this:
<asp:Label runat="server" ID="lblName" ClientIdMode="static"></asp:Label>
And that will generate this in html:
<span id="lblName"></span>
the code is picking up all the controls' ID and types, except labels
That's normal. The elements collection is only supposed to contain the form controls (and fieldsets for some reason). Labels aren't supposed to be in there.
$("div").each(function() { alert($(this).val()); });
Div and label elements don't have values, so that shouldn't work.
You can select HTML label elements easily enough though:
jQuery("#form1 label").each(function () {
jQuery("body").append("<p>Appending because alert is disabled in snippets</p>");
});
label {
display: block;
padding: 2px;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<label>Hello
<input name="hello" value="world">
</label>
<label>Goodbye
<input name="hello" value="world">
</label>
</form>
As Olivier points out though, make sure your HTML looks how you expect and that ASP.NET is generating the elements you are looking for with the correct types.
Related
I have a page which connects to a database where I have some users. Then, it takes each user and puts a div for each one of them, so I have 6 divs (a user in each div).
What I want is that, when somebody clicks in a div, it would give me the id of that user like if it was a form with an input.
I mean: the page takes the id and the name of each user from the database, so if I used a normal input, I would make that when the form is submitted, the form would return me the id of the selected user, but as I am using divs and no buttons, it would be nice to achieve that.
This is how my page looks (number 4 is where my mouse is):
The structure is basically, as I said, 6 divs, each one containing the name and the id of the user (I hide the names for privacy).
So, what can I do? If I haven't explained well I can give you more details... Thanks!!
Your HTML should be generated similar to this (each div has an attribute to point to its corresponding user from the DB)
<form id="select-user" action="formActionPage.php" method="POST">
<input id="selected-user" type="hidden" value="0">
</form>
<div id="1" class="user"></div>
<div id="2" class="user"></div>
<div id="3" class="user"></div>
The form has no submit button as you mentioned but has an input which is hidden notice that value=0 is a default value chosen by me .. you may control this in the action page ..
JQuery:
$("div").on('click', function() {
$('#selected-user').val($(this).attr('id'));
$('#select-user').submit();
});
EDIT
you may use div.[classname] div.user in my example, because you just don't want to apply this for any div
Use this:
HTML code:
<div><span id='userId'>10</span></div>
<div><span id='userId'>11</span></div>
jQuery code:
$("div").on('click', function() {
var userId = $("span", $(this)).text();
console.log(userId);
});
CSS code:
span {
display: none;
}
Main idea is to create in each div hidden span in which you will store user id, connected to this div. Also, you need onclick event, which will find this span and show needed id. Simple. Demo below.
DEMO
Note, that it is just an example. You can edit it as you need
I try set new value for input 'pid' attribute and get this, but I get null.
I have this code in jquery:
$(".feauter-product-holder").click(function () {
$("#productsubject").attr("pid", $(this).find("input[type=hidden]").attr("id"));
});
and my code in HTML:
<div class='feauter-product-holder'>
<input type="hidden" id="3">
</div>
<asp:TextBox runat="server" ID="productsubject" pid=""></asp:TextBox></div>
$.ajax({
url: editor.config.saveSubmitURL,//the url to post at... configured in config.js
type: 'POST',
data: { servicename: "savedata", text: data, subject: $("#productsubject").val(), pid: $("input[id$='productsubject").attr("pid") },//editor.name contains the id of the current editable html tag
})
i edit this post
i write wrong class div,but in my code is correct.
when i call pid in ajax i get null
What should I do?
Your DIV can't be found because of a wrong css class call. Try:
<div class="feauter-product-holder">
First of all remove "." from class name in DIV and then
you can try like this :-
$(".feauter-product-holder").click(function () {
$("input[id$='productsubject']").attr("pid", $(this).find("input[type=hidden]").attr("id"));
});
While Handling with ASP control with Jquery you use like (Element ends with selector)
example :- $("input[id$='productsubject']") .. $("#productsubject") won't work .
Actually in ASP.NET if you use asp control with some ID, ASP.NET Naming container changes the control ID like ctl001_yourcontrolID to avoid conflicts. Hence, in Jquery when you select a element by simply its ID(like $("#productsubject")) , you will not get that element since its ID has been changed. to illustrate, you can inspect the asp control in Firebug or chrome's inspect element.
Hence when you write $("input[id$='productsubject']") ,it select the element whose ID ends with productsubject.
You have 2 problems - the class on the div is incorrect, and also .net will change the id of the text box.
Try
<div class="feauter-product-holder">
for the div.
If you are using .net 4 you can set ClientIDMode="Static" on the text box like this
<asp:TextBox runat="server" ID="productsubject" pid="" ClientIDMode="Static"></asp:TextBox></div>
I am doing a portlet in Liferay with a form like this:
<form method="post" action="<%=actionAddRule.toString() %>" id="myForm" >
<aui:select name="attribute" style="float: left;">
<c:forEach var="attr" items="${fields}">
<aui:option value="${attr}" selected="${condition.attribute==attr}">${attr}</aui:option>
</c:forEach>
</aui:select>
<aui:input type='button' value="Add Condition" name='addCondition' onClick="addCondition();" %>'></aui:input>
<div id='conditions'></div>
</form>
I want that when someone click the button add a new select, but I don't know how do a new . I tried do it with JavaScript with:
var conditions = document.getElementById('conditions');
conditions.innerHTML('<aui:select ...>...</aui:select>');
and
document.createElement('<aui:select>');
I tried too with AUI script doing:
var nodeObject = A.one('#divAtr');
nodeObject.html('<aui:input type="text" name="segment21" label="Segment" value="lalal" />');
But it doesn't work because is html and doesn't can make AUI, and if I make the new select with HTML normal, when I catch the values some are lost.
Thanks.
As #Baxtheman stated, this won't work because the tag is not a client-side HTML tag, but a server-side tag from the aui-taglib.
To dynamically load the contents of the select box you would want to follow these steps:
add an element in your JSP, but make it hidden
<aui:select id="conditions" style="display: none;"><aui:select>
From your javascript, when the event occurs that you want to use to load your second select box, you would select the dropdown box and add the options you wish to it with something like the answer from this post Adding options to select with javascript
Make sure you set the select box to be visible after loading the options.
document.getElementById('<portlet:namespace/>conditions').style.display = 'block';
For more clarity, the reason you're missing information on POST if you add a normal HTML select box, is because of the way the aui:form serializes the data. I believe the ends up with a custom onSubmit that gathers only the aui elements.
<aui:select> is a JSP taglib, not the final HTML markup.
If you understand this, you resolve.
I am not a JavaScript person really, I write in ASP and use a SQL database in the backend. But our marketing director requested a change that will use JavaScript.
On our view cart page, we're currently displaying an input box with a modify button to allow customers to change the quantity of the listed item (in that row... there could be multiple products in their cart, each having their own quantity input).
<form method="post" action="updateitem.asp">
<input type="hidden" name="product_id" value="<%= PRODUCT_ID %>">
Quantity: <input type"text" name="quantity">
<input type="image" name="Submit" src="/graphics/modify.gif" align="middle" border="0" alt="Continue">
</form>
What I'd like to make work is something like this. Hrm, assuming I need to do my form/div name differently for each product? I can easily write the product_id into the id tags but then assuming I'd also need to loop through my function for each one. I've gotten this far in writing the replacement code:
Get Dataset from Database (items in cart) and loop through:
<form method="post" action="updateitem.asp" id="updateitems<%= PRODUCT_ID %>">
Quantity: <input type="text" name="qty<%= PRODUCT_ID %>" OnChange="Javascript:UpdateQty()")
<div id="showlink<%= PRODUCT_ID %>">
<br /><span class="BodyTiny">update</span>
</div>
</form>
END LOOP
So if the quantity changes, it displays the word "update" where they can click and it passes whatever quantity that is in the quantity field to the updateitem.asp (in a way I can then update it in the database in ASP/SQL). In the code above, if we could just insert the new # in the a href statement after quantity=, then I could fix it in the updateitems.asp page without a problem.
I'm not sure where to even begin honestly, I have this so far:
LOOP through dataset so each product has its own function
<script Language="JavaScript">
<!--
function UpdateQty(updateitems<%= PRODUCT_ID %>) {
Show div updateitems<%= PRODUCT_ID %>
Replace NEWQUANT within that div with the value in the input field qty<%= PRODUCT_ID %>
}
//-->
</script>
END LOOP
I'm having a few problems...
I am not sure how to write the function UpdateQty. It should A) display the stuff in div id=showlink, and B) add the # from the input named quantity quantity to the href so I can update it in the database on the next page
If they have JavaScript turned off, they should be able to enter a new quantity and just hit enter for it to submit the form. I believe this will work as its a form with 1 text input and 1 hidden one, so just hitting enter in the text input should submit it. But that should still work with whatever JavaScript is added to make the showlink div show if it changes.
Do I need to add a class to my CSS for showlink? If so, what do I need to put in it?
Any help would be greatly appreciated!
Mahalo!
so what you can do for updateQty is have one function that will be correct for all products in a list just by making a function that finds all the necessary elements by relative paths.
//in this function the context is the element, so the
//`this` variable can be used rather than a param
//for the product id
function updateQty() {
//show the update link
var parent = this.parentNode;
//assumes only the update text uses the class bodyTiny, and that there
//is only one element using it. obviously making this invariant true
//would be trivial by adding a different class name
var updateText = parent.getElementsByClassName("bodyTiny")[0];
updateText.style.display = 'block';
var updateLink = updateText.parentNode
, updateHref = updateLink.href;
//next we find the current quantity and replace it with the input
updateHref = updateHref.replace(/qty=(\d*)/, 'qty='+this.value);
//then we set the link element's attribute
updateLink.href = updateHref;
//now when you mouse over the link you should see the url has changed
}
You can also set your form to POST the equivalent data, and then I guess on the server side you will have your OnGetPage and OnPostback both delegate to the same method with the parameters either parsed out of the query string or out of the post data.
You can see it running on jsfiddle. Hopefully this helps!
How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.