How to focus next field if user clicked on the link? - javascript

I have a number of fields with labels-links like below:
<div class="control-group">
<label class="control-label" for="some-id-1">Text1</label>
<div class="controls">
<input type="text" id="some-id-1" name="some-id-1"><br>
</div>
</div>
<div class="control-group">
<label class="control-label" for="some-id-2">Text2</label>
<div class="controls">
<input type="text" id="some-id-2" name="some-id-2"><br>
</div>
</div>
If user clicks on the link, how can I focus according field (without preventing default action)? I.e. if user clicks on Text1, then I should open http://example.com/some-id-1 in new window and set focus at input with id some-id-1.

jsfiddle
$(".control-label a").click(function(){
$(this).parent().next().find('input').focus();
});

$('.control-label a').on('click', function(e) {
e.preventDefault();
$(this).parent().next().find('input').focus();
// or
$('.control-group').has(this).find('input').focus();
});

Text1

If understanding correctly you want to open a new page and in the new page set focus based on link that was clicked
If you are opening a new page you will need to pass a hash in url or use a cookie and have other page parse the hash or cookie
In current page:
$(function(){
$('.control-label a').click(function(){
var hash='#'+ $(this).next().find('input').attr('id');
window.open( this.href + hash);
return false;
});
})
In other page:
$(function(){
var hash= location.hash;
$(hash).focus();
})

JavaScript in one page can't control how another page responds to a URL, if the 'other' page is under your control then you could set it up to parse the id:
var parts = document.location.href.split('/'),
id = parts.pop();
document.getElementById(id).focus;
On the other hand, if you want to focus that element reliably, just pass an id, as a hash, to the URL:
Go to an element of 'some id'
This may not focus the form element, but it should draw that element to the attention of the user and, in pages outside of your control, is much more reliable.

Related

Why isn't jQuery append method working when passing parent class to add a child input?

I want to append a duplicate of an input box in a parent box. Here is my HTML structure:
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
And here is my jQuery code:
function addPlaceholder(parentClass){
var placeHolder = $(parentClass).children().eq(0);
$(parentClass).append(placeHolder);
console.log(placeHolder);
}
$('.add-reading-btn').click(function(){
addPlaceholder('.reading-group');
});
Here is the jsfiddle link: https://jsfiddle.net/abhishekraj007/kexe6gxn/
What am I doing wrong?
Your code is taking the existing <input> element and moving it from the <div> and back into the <div>, so it looks like nothing is happening. If you .clone() the element and then .append() it, a new element will be added.
Here is a working example:
function addPlaceholder(parentClass) {
var placeHolder = $(parentClass).children().eq(0).clone();
$(parentClass).append(placeHolder);
console.log(placeHolder);
}
$('.add-reading-btn').click(function() {
addPlaceholder('.reading-group');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
If you want to add focus to your <input> element on load, you can do so by adding this line to the bottom of your code:
$('#link').focus();
If you want to add focus to the new element on creation, as well as give it an empty value rather than copying the prior element's value, add this line to the end of your addPlaceholder() function:
$(placeHolder).val("").focus();
you can just add the .clone() method of jquery to create a clone of the textbox like below . You were only referring to the same element not the cloned html before.
$(document).ready(function(){
function addPlaceholder(parentClass){
var placeHolder = $(parentClass).children().eq(0).clone();
$(parentClass).append(placeHolder);
//console.log(placeHolder);
}
$('.add-reading-btn').click(function(){
addPlaceholder('.reading-group');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
Here is a working fiddle
https://jsfiddle.net/kexe6gxn/2/

Get new content from ajax function and replace it on click

I have a single page with a div that gets new content when a user click on a radio button, when the page is loaded it display the main content, when user click on X radio button, that content gets "re-new" or "different" information, there is a DIV id that doesn't change... so...
When user loads the page, I check fro some values, is X value is lower than then replace the div content, on the first load it works fine, but if the user changes options then the first script wont do nothing... so here is the basic html
<div id="options">
<input type="radio" onclick="javascript:checkOut(this.name,'shipr');" value="1" name="shipping" id="s1">
<input type="radio" onclick="javascript:checkOut(this.name,'shipr');" value="2" name="shipping" id="s2">
<input type="text" id="qty" class="hidden" value="1.2" style="display: none;">
</div>
<div id="information">
<div id="prices>$120.00</div>
<div id="products">Multiple[...] and tabs long list</div>
<div id="checkoutbtn">Buy Now</div>
</div>
Basically when user click on any of the radio buttons the content of the div "information" gets replace by ajax information, I'd like to know how do I get the new content and "replace" some values...
Now, the input with the ID qty that is hidden has the value I need is that value is less or grater than I replace the button inside the div with the id checkoutbtn from "buy now" to "Only inside US and UK, please Request a quote"... so, my JS is:
(function($) {
var pkg = $("#qty").val();
var cot = '<a rel="{handler: \'iframe\', size: {x: 570, y: 550}}" ' +
'class="modal" href="qut.php">' +
'<input type="button" value="Quotation" class="btn btn-small">' +
'</a>';
window.onload = function() {
if (pkg < 4 ) {
// do something
// alert('Checked');
$('#checkoutbtn').html(cot);
}
};
$('input:radio[name="shipping"]').change(
function(){
if ($(this).is(':checked') && $(this).attr("id") == 's1') {
// alert(pkg);
$('#checkoutbtn').html(cot);
} else if ($(this).is(':checked') && $(this).attr("id") == 's2') {
$('#checkoutbtn').html(cot);
}
});
})(jQuery);
When the page is load for the first time it works fine, and if it wasn't for the ajax that change the content of the div with the id information it would be flawless, but is not...
As you can see I have this piece of code: $('input:radio[name="shipping"]').change() ... so now I need something that would give some time to load the new content or to check when the new content is ready and then execute this other code $('#checkoutbtn').html(cot); ... the question is, how do I do that... if I put a timeout of 2 seconds it might work, but sometimes it takes 3 or 5 seconds for the new information to be ready and available to the user and that would be a problem...
So, I need to check when the new content is ready after the user has click on the radio button, how do I do that?
Thank you.

Unable to prevent user from going back to previous Log In page

Currently the users see login page when they open the application. Upon signing in, they get into the main page. I want to prevent the user from going back to the login page once they are logged in which the user can easily do by just clicking on the back button on the phone or the web browser.
The following method does that by preventing me from going back or forth to the page I want. For example if I identify the id as #home, it is going to prevent me from going back to homepage. Problem is this works for all my pages in my application less the one page I actually want to enforce this on which is my login page. When I use the login page's id, nothing happens and I am able to go back to the login page by clicking the back button. Please advise what I am doing wrong.
JS
// triggers when leaving any page
//this doesn't work cos I am using the id of my loginpage. Other page's ids works.
$(document).on('pagebeforechange', function (e, data) {
var to = data.toPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (to === '#loginForm') { //will work if I use #benefits for example.
alert('Can not transition the page!');
$.mobile.changePage("#home", {
transition: "flip"
});
e.preventDefault();
e.stopPropagation();
// remove active status on a button, if transition was triggered with a button
$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-shadow').css({
'box-shadow': '0 0 0 #3388CC'
});
}
}
});
HTML for LOG IN Page
<div data-role="page" id="loginForm" data-theme="e" data-add-back-btn="false">
<header data-role="header">
<h1>Log In</h1>
</header>
<form id="form1" name="form1" method="GET" action="http://example.com">
<label for="id">Username </label>
<input type="text" name="id" id="id" />
<label for="password">Password </label>
<input type="password" name="password" id="password" />
<input type="hidden" name="rank" id="rank" value="123">
<input type="submit" name="submit" value="Login"/>
</form>
</div>
HTML for Benefits Page
<div data-role="page" id="benefits" data-theme="e">
<header data-role="header">
<h1>Benefits</h1>
</header>
<article data-role="content" >
<div data-role="collapsible-set" id="benefitsList">
<!--will fill up with info from database-->
</div>
</article>
</div>
EDITED:
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = $.mobile.pageContainer.pagecontainer("getActivePage");
$.mobile.pageContainer.pagecontainer("change", current);
}
}
});
The problem that the code above works on all pages except for first page loaded, is because - by default - jQM doesn't change hash in URL for first page. The code above checks if there retrieves hash from URL, since there is no hash for first page, it returns false and thus doesn't prevent user from going back to "login page".
The code below checks URL and compares it with .url of first page loaded. The .url is stored in $.mobile.navigate.history.stack and it has 0 index, since it is first page.
jQuery Mobile 1.4
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = "#" + $.mobile.pageContainer.pagecontainer("getActivePage")[0].id;
window.location.hash += current;
return false; /* this will stop page change process */
}
}
});
jQuery Mobile <= 1.3
Change
$.mobile.navigate.history.stack[0].url
to
$.mobile.urlHistory.stack[0].url
Change
$.mobile.pageContainer.pagecontainer("getActivePage")[0].id
to
$.mobile.activePage[0].id
Demo - Code

jQuery cannot recognize appended cloned elements using jQuery.appendTo()

I want to make a list of group inputs allow user to dynamically let user add/remove group row:
<div id="div-form-denominations" class="form-denominations">
<div id="row-0" class="form-denomination">
<div class="form-field">
<div class="form-field">
<div class="form-field">
<input id="_denominations[0].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[0].id.reference" value="87-070329-034COP-4444">
<input id="_denominations[0].denomination" class="removableHiddenDenom" type="hidden" name="denominations[0].denomination" value="10000">
<a id="deleteBtn-[0]" class="action-link delete-denomination" href="#">
<div class="spacer"></div>
</div>
<div id="row-1" class="form-denomination">
<div class="form-field">
<div class="form-field">
<div class="form-field">
<input id="_denominations[1].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[1].id.reference" value="87-070329-034COP-4444">
<input id="_denominations[1].denomination" class="removableHiddenDenom" type="hidden" name="denominations[1].denomination" value="">
<a id="deleteBtn-[1]" class="action-link delete-denomination" href="#">
<div class="spacer"></div>
</div>
<div id="row-2" class="form-denomination">
<div class="form-field">
<div class="form-field">
<div class="form-field">
<input id="_denominations[2].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[2].id.reference" value="">
<input id="_denominations[2].denomination" class="removableHiddenDenom" type="hidden" name="denominations[2].denomination" value="">
<a id="deleteBtn-[2]" class="action-link delete-denomination" href="#">
<div class="spacer"></div>
</div>
<div id="row-3" class="form-denomination">
.......
</div>
So each row include a group of form-field which include an input or select component(not show in above code) and some hidden fields and a delete link to remove current row from view.
Also I create a link to dynamic add a new row into the section
var rowTemplate = null;
j(document).ready(function() {
// Save the row template
rowTemplate = j('.form-denomination:first-child').clone();
j("#add_link").click(function() {
add_denomination();
});
});
and here is the content of add_denomination function that clone the first row and replace any cloned id with new index, and append the cloned row after last row of the list.
function add_denomination() {
var index = j('.form-denomination').length;
// set the new row id
var newRowId = 'row-' + index;
var newRow = rowTemplate.clone().attr('id', newRowId);
// Replace the id/name attribute of each input control
newRow.find('div, input, select, a').each(function() {
replaceAttribute(j(this), 'id', index);
replaceAttribute(j(this), 'name', index);
j(this).val('');
});
// add new element to the DOM
newRow.appendTo('.form-denominations');
alert("new list size = " + j(".delete-denomination").length);
console.log("DONE!");
}
each time click on the add-link the pop up alert show the new list size (j(".delete-denomination").length increment by 1), which in my understanding, new row appended successfully.
The problem is the following method
// delete denomination row
j('.delete-denomination').click(function () {
j(this).parent().remove();
}
ONLY WORKS FOR THE NON-CLONED ROW !!! Using firebug I can clearly see the appended row is successfully appended with same structure and same element as original rows but only difference is the id.
However, each time when I click on deleteBtn-[i], in which i is the cloned/appended row's index, the code even not going into the j('.delete-denomination').click() function, which in my understanding, Dom or jquery didn't recognize the new rows hence the failure of identifying the link by jQuery. It's kind of contradictory to the previous alert message that telling the size of list has grown.
But when I click on deleteBtn-[i] where i is the non-cloned row, everything works fine...
So the question is: how to append/add new doms and make them identified by jQuery or Dom? What is wrong in above processing? Is there any way to refresh the list so that Dom/jQuery understand the appended rows from all perspective?
jQuery 1.7+
j(".form-denomination").on("click", ".delete-denomination", function(){
j(this).parent().remove();
});
jQuery 1.3+
j(".delete-denomination").live("click", function(){
j(this).parent().remove();
});
jQuery 1.4.3+
j(".form-denomination").delegate(".delete-denomination", "click", function(){
j(this).parent().remove();
});
The problem is a matter of order and when expressions are evaluated. When you call jQuery with a selector, the selector is evaluated at that time to select the matching elements which exist at that time. The click handler is then registered to only those elements. Elements which are created later are, naturally, not affected.
One solution, demonstrated in another example, uses jQuery's "live events" to apply the selector at the time each event is fired to determine what elements, if any, it would match. There is a performance implication to this approach.
Another solution is to register the desired event handler on the newly created elements when you create them.
Add 'true' to the clone method in order to copy the data as well as the events attached to the original element.
rowTemplate = j('.form-denomination:first-child').clone(true);
This is disabled by default. Here is the clone documentation:
https://api.jquery.com/clone/
P.s. You don't need the click function within the document.ready and it won't bind until after the click.

Pass Info to form input when link is clicked

I have some html that looks as so:
<h3 class="basic left-top-border-radius">Basic<br /> 500<span>$25</span></h3>
<a class="signup colorbox" href="#text-signup-form">More Info</a>
When More Info is clicked a lightbox pops up with a simple info request form. Here is my problem. I would like when the link is clicked to have the text of the h3 header passed to a form input field that is hidden so I know which plan they clicked on for more info.
The input looks like so:
<input type="text" class="cat_textbox" id="CAT_Custom_440761" name="CAT_Custom_440761" maxlength="1024" />
How would I do this using jQuery? (I thought of using jQuery .text() method but I read that does not work with forms and I do not know how to pass the h3 text anyway.
NOTE There are multiple h3 elements on the page.
You can do the following with this code.
$('.signup').click(function(){
var planTitle = $('h3').text();
$('#CAT_Custom_440761').val(planTitle);
});
As you click on the button it will search for the h3 tag (would be better to attach an ID to the h3 tags) grab the text of that element and insert it into the value of the input field.
If you aren't able to attach an ID to the h3 tag you can search for the prev instance of h3 and take the text from that.
$('.signup').click(function(){
var planTitle = $(this).prev('h3').text();
$('#CAT_Custom_440761').val(planTitle);
});
You can try this:
$('a').click( function() {
var text = $(this).parent().find('h3').text();
$(this).parent().find('.cat_textbox').val(text);
})
perhaps you can use this code
<form action="test1.asp" id="testform">
<input type="hidden" id="test3" value="">
<input type="BUTTON" id="submit" onclick="modify_value()"/>
</form>
<script type="text/javascript">
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'testvalue';
document.getElementById("testform").submit();
}
</script>

Categories

Resources