jQuery Clone() not behaving as it should within asp.net page - javascript

I have a search box that needs to be within a form so that it can post to another page for a search functionality to work.
I originally had this working fine in Firefox by using an iFrame, but using the search box would simply refresh the when using Internet Explorer.
I found out that it worked fine if I simply created another form underneath the current one, however this obviously leaves it in the wrong place on the page.
I attempted to use the jQuery clone() method that I have succesfully used elsewhere on the site, but this is refusing to work.
I looked around and found another way of using the clone() method and I have it working fine within jsfiddle, but it will not work on my site.
This is the div that I want to populate:
<div id="CustomerSearch">
2
</div>
And this is the div that I want to be cloned:
<form name="frmCustomerList" action="../CustomerList/default.asp" method="post">
<div id="CustomerSearchClone">
1
Customer Search: <br />
<input type="text"id="txtSearch" name="txtSearch" class="Searchbox" />
<input type="submit" value="View" name="txtSearchSubmit" />
</div>
</form>
This is the script that I am using in an external file:
var CustomerSearch = jQuery('#CustomerSearch');
var CustomerSearchClone = jQuery('#CustomerSearchClone');
CustomerSearch.html(CustomerSearchClone.clone(true));
I have it working in JSFiddle here: http://jsfiddle.net/de9kc/92/
Any ideas?
Thanks guys

I'm not a .NET guy but the div you are pasting too is still within a form tag so I'm not certain that this wouldn't cause a hiccup for .NET at submission time (or postback, or whatever).
However, with respect to getting the cloned form elements where you wanted them per the layout you demonstrate in your question;
I modified the pre-result html like so:
//html
<form id="form1" runat="server">
<div id="CustomerSearch">2 Customer Search:</div>
</form>
<form name="frmCustomerList" action="../CustomerList/default.asp" method="post">
<div id="CustomerSearchClone">1 Customer Search:
<br />
<input type="text" id="txtSearch" name="txtSearch" class="Searchbox" />
<input type="submit" value="View" name="txtSearchSubmit" />
</div>
</form>
then i used this jQuery:
// the vars you already created
var CustomerSearch = jQuery('#CustomerSearch');
var CustomerSearchClone = jQuery('#CustomerSearchClone');
// using .clone(true, true) for deepWithDataAndEvents - not sure if you want this?
// will the .clone(true, true) retain input's link to original form id? I'm uncertain
// using .children() because clone's intended destination already has a div container
CustomerSearchClone.children().clone(true, true).appendTo(CustomerSearch);
// hide clone's source after cloning; no sense in having both search boxes visible
CustomerSearchClone.hide();
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. (per http://api.jquery.com/clone/)
But you are appending the cloned elements into a different form tag, so maybe a non-issue.
I'm just learning jQuery myself, but I thought I would give the solution a shot ;-$
JSFiddle here: http://jsfiddle.net/de9kc/190/

Related

Form using Javascript exclusively

I have an assigment, I don't understand it as i'm beginner.
Create a javascript script which will modify the DOM of a web-page.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?".
Thank you in advance.
I need to use only Javascript for this and I can only find answers
that use HTML
Web applications use HTML to contain, render and display elements in the viewport (browser window).
Where do you intend to render the form and capture user input?
You can build the DOM structure using JavaScript alone, however, there will still be a HTML file, which will contain the HTML elements created using javascript.
Please provide clarity as to your desired goal and what type of application this is being used for.
My gut feeling, for simplicity, is that you will require to use HTML as your template file, and JavaScript for interactivity and manipulation of the HTML file.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?". That's it.
This is a start, just to try to help you to understand the concepts.
I do, however, implore you to go and explore with confidence - you won't break anything, just give it a try!
I recommend you try taking a look at some of these articles, have a look at my (very rudimentary) code below, and feel free to ask any questions you have!
JS:-
W3 Schools JS and HTML reference
HTML:-
W3 Schools: HTML Forms
W3 Schools: Label Tag
W3 Schools: Text Area Tag (This has been left out of the solution on purpose - give it a try!!)
(function divContent() {
//Create a 'div' as a container for our form
var div = document.createElement('div');
// Perhaps you could style it later using this class??
div.className = 'row';
// I have used backticks to contain some more normal looking HTML for you to review, it's not complete though!!
div.innerHTML = `<form action="javascript:" onsubmit="alert('Your message here, or, run a function from your JavaScript file and do more stuff!!')">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="Mickey Mouse">
<br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="mickey#mouse.co.uk">
<br><br>
<input type="submit" value="Submit">
</form> `
// Get the body of the document, and append our div containing the form to display it on page
document.getElementsByTagName('body')[0].appendChild(div);
}());
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="CoderYen | Wrangling with 0s & 1s Since The Eighties">
</head>
<body>
</body>
</html>

Javascript returns undefined with asp.net master pages

I'm running into a bit of an issue. My JavaScript function returns "undefined" when using master pages. However, when I'm not using master pages, it works fine. Here is my code:
HTML:
<input id="txtPhoneNumberAreaCode" class="TextBox" runat="server" type="text" onkeyup="GoToNextTextBox(this.id, 3, 'cphMainArea_txtPhoneNumberFirstThree')" />
The Javascript:
function GoToNextTextBox(CurrentTextBox, MaxCharLength, NextTextBox) {
alert(CurrentTextBox.value);//pops up "undefined"
if (CurrentTextBox.value.length == MaxCharLength) {
NextTextBox.focus();
NextTextBox.style.backgroundColor = '#FFFFFF';
}
Again, this works fine when not using master pages. So I'm completely confused.
This is because, you are doing it wrong.
In GoToNextTextBox(), you are expecting a DOM element, but you are passing only its id.
DO this:
<input id="txtPhoneNumberAreaCode" class="TextBox" runat="server" type="text"
onkeyup="GoToNextTextBox(this, 3, 'cphMainArea_txtPhoneNumberFirstThree')" />
When using master pages and user controls the rendered ID of your controls change, but there is a way to stop it.
Let's say you have a Textbox
<asp:Textbox id="txtName" runat="server"></asp:Textbox>
on a standard asp page, it's id will be as you expect, txtName
Now you add a master page, called Site.Master. In your rendered html, the controls name is now different.
cntl1_Site_txtName
I might have the syntax of the new name a bit off, but you can view source and find it for yourself.
There is a way to control that though. There is a property on your page, ClientIDMode.
If i remember correctly it has 3 or 4 options. Auto ID is default I believe.
If you set it to static for that page, then you will no longer get the verbose control IDs, they will be as you expect.
This can be a downfall when using things like Repeaters though. You will not have easy access to specific fields if they do not have the verbose ID

Dynamic forms AUI Liferay

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.

How to unlock a jquery ui check button when content is replaced with Backbone.js?

I have a web application which replaces content. This content has jquery ui check buttons. When I replace the content if a button already exists then don't add it again:
if(!$('label[for=checkWeekM]').hasClass('ui-button'))
$('.checkWeek').button();
If I push the button (its state is checked) and if I replace the content, the button starts locked until the same content is replaced again.
I use Backbone.js to replace the content
jsfiddle
How can I unlock the check button?
You are duplicating id attributes and that leads to bad HTML, bad HTML leads to frustration, frustration leads to anger, etc.
You have this in your template that you have hidden inside a <div>:
<input type="checkbox" class="checkWeek" id="checkWeekM" />
<label for="checkWeekM">L</label>
Then you insert that same HTML into your .content-central. Now you have two elements in your page with the same id attribute and two <label> elements pointing to them. When you add the jQuery-UI button wrapper, you end up with a slightly modified version of your <label> as the visible element for your checkbox; but, that <label> will be associated with two DOM elements through the for attribute and everything falls apart.
The solution is to stop using a <div> to store your templates. If you use a <script> instead, the browser won't parse the content as HTML and you won't have duplicate id attributes. Something like this:
<script id="template-central-home" type="text/x-template">
<div data-template-name="">
<input type="checkbox" class="checkWeek" id="checkWeekM" />
<label for="checkWeekM">L</label>
</div>
</script>
and then this to access the HTML:
content.view = new ContentView({
model: content,
template: $('#template-' + template_name).html()
});
Demo: http://jsfiddle.net/ambiguous/qffsm/
There are two quick lessons here:
Having valid HTML is quite important.
Don't store templates in hidden <div>s, store them in <script>s with a type attribute other than text/html so that browser won't try to interpret them as HTML.
I took a detailed look at your fiddle after you mentioned this problem. The solution I suggested here was more like a quick fix.
If you want to follow the right thing to avoid long term problems and side effects you should consider what is mentioned here. This way your problem is solved and there are no other bugs.

jquery text input box pass to variable

This is my first time using jquery and while this is a fairly simple task I'm stuck already.
I've got a input box with the time of day in it. I would like to create a button to grab the time and send it to a variable (setTime) so I can use the time elsewhere in the script.
However I'm having trouble the variable to pass, I've added an alert window but all I get is either a blank alert or an "undefined" alert.
The first line Start Time.... works fine its the setTime stuff that's broken.
Page header:
setTime = $('#setTime').text();
$('#formTime').timeEntry({show24Hours: true});
Page body:
<p>Start Time <input type="text" size="2" id="formTime" class="spinners" value="" /> </p>
<input type="button" value="Set Time" onclick="$('#setTime').val('#formTime');" />
<input type="button" value="Show Date" onclick="alert(setTime);" />
Thanks
You have to make a few changes to your code.
Update your Html by adding some ids for example.
<p>
Start Time <input type="text" size="2" id="formTime" class="spinners" value="" />
</p>
<input id="setTime" type="button" value="Set Time" />
<input id="showTime" type="button" value="Show Date" /> ​
Personally I don't like assigning script to events within the html controls as they become hard to maintain and add clutter to the page.
You can write script at the bottom of the html page within a script tag or better yet, use an external js file. External js files will also keep your Html clean and your scripts unobtrusive.
var setTime = 0;
var $fromTime = $("#formTime")
$("#setTime").off("click").on("click", function(){
setTime = $fromTime.val();
});
$("#showTime").off("click").on("click", function(){
alert(setTime);
});
See working DEMO
Using jQuery can be confusing at times but the on-line documentation is fantastic.
#setTime means "The element with the id 'setTime'" - you have no element with that id, and the control you are trying to get the value of has no id at all.
timeEntry is not a jQuery method, so will error when you try to call it. If you are using a plugin that you think should add that method then you should say so.
.val('#formTime') will set the value of a form control to the string #formTime. If you want to get the value, don't pass that method an argument … and do assign the return value of the method call to something.
You should probably work through an introduction to programming and JavaScript.

Categories

Resources