Modal dialog of the url not working? - javascript

Sorry this is driving me nuts but my modal dialog box is not showing up when I switch button to a link. Basically for this functionality (sorry I had to take company sensitive data out so some of the code is missing but still works) I just want the editors to put in a link with an id or class and that link doesn't work but the address opens a dialog box with the address url in it.
I have this working with a button but this does not work with a link and code below. Also they are manually entering link into p-tag and wondering if it can be captured via href.
$(function() {
var dialog, form,
tips = $( ".validateTips" );
function addUser() {
var valid = true;
allFields.removeClass( "ui-state-error" );
valid = valid && checkLength( name, "username", 3, 16 );
valid = valid && checkLength( email, "email", 6, 80 );
valid = valid && checkLength( password, "password", 5, 16 );
valid = valid && checkRegexp( name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter." );
valid = valid && checkRegexp( email, emailRegex, "eg. ui#jquery.com" );
valid = valid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
if ( valid ) {
$( "#users tbody" ).append( "<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>" );
dialog.dialog( "close" );
}
return valid;
}
dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser();
});
$( "#create-link" ).a().on( "click", function(e) {
e.preventDefault();
dialog.dialog( "open" );
});
});
<div>Perma-link</div>
<div id="dialog-form" title="Link Address">
<p class="validateTips">https://xyz</p>
</div>
Note - I completely understand that it is odd to capture a link in a modal box but we must do this because the vendor does not display the full active link in the url. So when our users try to share the page they copy the url in browser which takes other users no where. The link here takes them to the permanent page. I know this is stupid but needed.

When you look up an element with a jQuery selector, it returns a jQuery object that you can call jQuery defined methods on.
In your code, you have:
$( "#create-link" ).a().on( "click", function(e) {
e.preventDefault();
dialog.dialog( "open" );
});
The object returned by $("#create-link") is a jQuery object of the a tag in your html. You can only call jQuery methods on that object. The method a() is not defined as far as I know in jQuery or jQuery UI. Remove that.
As for the link itself, it doesn't make sense to add a link and then block the action of clicking the link. I'm guessing you aren't understanding the requirements, based on this comment:
the UI guys wanted me to hand it over as a link. So the last part of
this was moving the button to a link and then making the href
automatically populate the validateTips section
That reads to me like they want you to provide the user with a link.

I don't think your click event is firing when you click the link. Why not say
$( "#create-link" ).on( "click", function(e) {
e.preventDefault();
dialog.dialog( "open" );
});
Simply removing the a(). should fix things.
See here http://jsfiddle.net/eos4c25w/1/

Related

JS YouTube Regex With Empty input acceptable

I have a youtube input for the embedding code and I wish to be able to also have the user not necessarily have to input a youtube embed. But I'm stuck about how to alter my regex to accept an empty field... I have set errors if the user fails the regex and no errors if the user passes the regex, So I would imagine there would be a simple fix to the regex to accept an empty input value.
Can anybody see how I would achieve this from my code below...
Thank you for any advice.
function checkyoutube() {
var youtube = $("#youtubevalue").val();
//var youtubeReg =/^[a-zA-Z][a-zA-Z0-9-+&%#=?<>()£~_\.*#$!, \r\n]{0,300}$/;
var youtubeReg =/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((.|-){11})(?:\S+)?$/;
if(!youtubeReg.test(youtube)) { localStorage.setItem('error', 'true');
$("#youtubefooter").text("Example https://youtu.be/12KxXnFbwbU"), $( "#youtubevalue" ).addClass( "errorclass" ), $( "#youtubevalue" ).removeClass( "noerrorclass");
}
if(youtubeReg.test(youtube)) { localStorage.setItem('error', 'false');
$("#youtubefooter").text("URL Is Good, Thanks!"), $( "#youtubevalue" ).addClass( "noerrorclass" ), $( "#youtubevalue" ).removeClass( "errorclass");
}
var youtubeB = document.getElementById('youtubevalue');
(var regex= LOTS / OF / BAD / WORDS;)'EDITED FOR STACK'
youtubeB.value=youtubeB.value.replace(regex, "****");
};
You could make the regex optional ? by using a non capturing group (?:.....)?
^(?:(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((.|-){11})(?:\S+)?)?$
var youtubeReg = /^(?:(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((.|-){11})(?:\S+)?)?$/;
var strings = [
'https://youtu.be/12KxXnFbwbU',
'',
'https://youtu'
];
strings.forEach((s) => {
console.log(s + ' ==> ' + youtubeReg.test(s));
});
Must it be done with regex? If not, you could simply trim the input and check if its empty, if empty then its good and if not apply regex.
See the below code
function checkyoutube() {
var youtubeReg =/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((.|-){11})(?:\S+)?$/;
var youtube = $("#youtubevalue").val();
//checking for length here after trimming
if(youtube.trim().length==0||youtubeReg.test(youtube)) { localStorage.setItem('error', 'false');
$("#youtubefooter").text("URL Is Good, Thanks!"), $( "#youtubevalue" ).addClass( "noerrorclass" ), $( "#youtubevalue" ).removeClass( "errorclass");
}
else{//skipped testing for regex again here
localStorage.setItem('error', 'true');
$("#youtubefooter").text("Example https://youtu.be/12KxXnFbwbU"), $( "#youtubevalue" ).addClass( "errorclass" ), $( "#youtubevalue" ).removeClass( "noerrorclass");
}
var youtubeB = document.getElementById('youtubevalue');
(var regex= LOTS / OF / BAD / WORDS;)'EDITED FOR STACK'
youtubeB.value=youtubeB.value.replace(regex, "****");
};

jQuery mobile nested-list plugin bug going back

I'm using the 'nested-list' plugin for jQuery Mobile, this one:
The problem is that when you use more than one level the plugins fails going back. For example, in the fiddle I have created I can go to 'Test 1.2.1' without problem, If I going back 1 level it works fine and I go to 'Test 1.2', but then if I tried to go up one level more (it was 'Test1') it goes up 2 levels (to 'Test').
I have checked the plugin code but I can't find the problem and I have left a message in the Git forum with no answer. Maybe someone could help me here.
Thanks in advance!
Fiddle
Looking at the plugin code, it is only designed for one level deep nesting. This is because the developer chose to remove created subpages each time you click on a parent LI. So when you get to the second level of depth, its parent has been removed from the DOM and you have to click the back button twice to get to the original page.
I have made some changes to the plugin code that should solve this problem:
In _attachBindings, I have commented out the line that removes previously created subpages:
_attachBindings: function() {
this._on({
"click": "_handleSubpageClick"
});
this._on( "body", {
"pagechange": function(){
if ( this.opening === true ) {
this.open = true;
this.opening = false;
} else if ( this.open === true ) {
//Don't remove the old LI
//this.newPage.remove();
this.open = false;
}
}
});
},...
Then in _handleSubpageClick, I check if the subpage already exists in the DOM (via data attribute added when creating the page). If not, we go through the existing code that creates the subpage, and then in the end I store the created subpage id in a data attribute on the parent LI. If it does exist we just navigate to that page.
_handleSubpageClick: function( event ) {
if( $(event.target).closest( "li" ).children( "ul" ).length == 0 ) {
return;
}
this.opening = true;
//see if we already created the subpage
var $li = $(event.target).closest( "li" );
var pid = $li.data("nextpageid");
if (pid && pid.length > 0){
this.pageID = pid;
} else {
this.newPage = $( this.options.page ).uniqueId();
this.nestedList = $( event.target ).children( "ul" )
.clone().attr( "data-" + $.mobile.ns + "role", "listview" )
.css( "display", "block" );
this.pageName = (
$( event.target.childNodes[0] ).text().replace(/^\s+|\s+$/g, '').length > 0 )?
$( event.target.childNodes[0] ).text() : $( event.target.childNodes[1] ).text();
this.pageID = this.newPage.attr( "id" );
// Build new page
this.newPage.append(
$( this.options.header ).find( "h1" ).text( this.pageName ).end()
).append(
$( this.options.content )
).find( "div.ui-content" ).append( this.nestedList );
$( "body" ).append( this.newPage );
//save subpage id as data attribute of the LI
$li.data("nextpageid", this.pageID);
}
$( "body" ).pagecontainer( "change", "#" + this.pageID );
}...
Here is your updated FIDDLE
I removed the external link to the plugin and instead copied all the code into the javascript pane and made the edits. You should be able to copy that code directly and use as the updated plugin. (Of course I did this quickly and have not rigorously tested it, so make sure it works for you).

Jquery Mobile 1.4 swipe demo in Chrome with mobile device

My question concerns the swipe event on a mobile device (I'm using a Nexus 7) with Chrome. I am working off the Jquery Mobile 1.4.2 demo which can be found here:
http://demos.jquerymobile.com/1.4.2/swipe-page/
I'll ask my question and copy the sample javascript below. I can get everything to work, both on my laptop (using Chrome) and on my tablet (using Firefox), but the swipe works maybe one out of ten times in Chrome with my tablet. Any advice? Thanks!
// Pagecreate will fire for each of the pages in this demo
// but we only need to bind once so we use "one()"
$( document ).one( "pagecreate", ".demo-page", function() {
// Initialize the external persistent header and footer
$( "#header" ).toolbar({ theme: "b" });
$( "#footer" ).toolbar({ theme: "b" });
// Handler for navigating to the next page
function navnext( next ) {
$( ":mobile-pagecontainer" ).pagecontainer( "change", next + ".html", {
transition: "slide"
});
}
// Handler for navigating to the previous page
function navprev( prev ) {
$( ":mobile-pagecontainer" ).pagecontainer( "change", prev + ".html", {
transition: "slide",
reverse: true
});
}
// Navigate to the next page on swipeleft
$( document ).on( "swipeleft", ".ui-page", function( event ) {
// Get the filename of the next page. We stored that in the data-next
// attribute in the original markup.
var next = $( this ).jqmData( "next" );
// Check if there is a next page and
// swipes may also happen when the user highlights text, so ignore those.
// We're only interested in swipes on the page.
if ( next && ( event.target === $( this )[ 0 ] ) ) {
navnext( next );
}
});
// Navigate to the next page when the "next" button in the footer is clicked
$( document ).on( "click", ".next", function() {
var next = $( ".ui-page-active" ).jqmData( "next" );
// Check if there is a next page
if ( next ) {
navnext( next );
}
});
// The same for the navigating to the previous page
$( document ).on( "swiperight", ".ui-page", function( event ) {
var prev = $( this ).jqmData( "prev" );
if ( prev && ( event.target === $( this )[ 0 ] ) ) {
navprev( prev );
}
});
$( document ).on( "click", ".prev", function() {
var prev = $( ".ui-page-active" ).jqmData( "prev" );
if ( prev ) {
navprev( prev );
}
});
});
$( document ).on( "pageshow", ".demo-page", function() {
var thePage = $( this ),
title = thePage.jqmData( "title" ),
next = thePage.jqmData( "next" ),
prev = thePage.jqmData( "prev" );
// Point the "Trivia" button to the popup for the current page.
$( "#trivia-button" ).attr( "href", "#" + thePage.find( ".trivia" ).attr( "id" ) );
// We use the same header on each page
// so we have to update the title
$( "#header h1" ).text( title );
// Prefetch the next page
// We added data-dom-cache="true" to the page so it won't be deleted
// so there is no need to prefetch it
if ( next ) {
$( ":mobile-pagecontainer" ).pagecontainer( "load", next + ".html" );
}
// We disable the next or previous buttons in the footer
// if there is no next or previous page
// We use the same footer on each page
// so first we remove the disabled class if it is there
$( ".next.ui-state-disabled, .prev.ui-state-disabled" ).removeClass( "ui-state-disabled" );
if ( ! next ) {
$( ".next" ).addClass( "ui-state-disabled" );
}
if ( ! prev ) {
$( ".prev" ).addClass( "ui-state-disabled" );
}
});
I've done the same experiment and I've observed similar results with my tablet (Nexus 7 - Google Chrome).
You should not use heavy frameworks like jQueryMobile if you are going to create a web app or a mobile website because even if these tools make your life easier at the end the result, especially on Android devices, will be slow and sluggish.
In other words you should create your own .css and .js.
If you need to manipulate the DOM very often you should also look for alternatives to jQuery.
I suggest that you use Zepto.js.
In the end, I decided to use the jQuery touchSwipe plugin and write my own code, works fine in different browsers and across devices. Some of this may not make sense without the HTML, but essentially I determine the direction of the swipe based on the variable that is passed into the method. Then, by getting various attributes and class names, I am turning on and off the display of the various divs that have previously loaded the JSON into them from another method. The way I do that is through substrings, where the last digit of the id is a number. If anyone has any comments about how this code could be more efficient, I'd be happy to hear your thoughts. Cheers.
function swipeLiterary() {
$("#read").swipe({
swipe:function(event, direction, distance, duration, fingerCount) {
switch (direction) {
case 'left':
var thisPage = $('.display').attr('id');
var nextPageNum = parseInt(thisPage.substring(8)) + 1;
var nextPage = thisPage.substring(0,8) + nextPageNum;
if (nextPageNum > 9) {
break
}
$('#' + thisPage).removeClass('display').addClass('nodisplay');
$('#' + nextPage).removeClass('nodisplay').addClass('display');
console.log(nextPage);
break;
case 'right':
var thisPage = $('.display').attr('id');
var prevPageNum = parseInt(thisPage.substring(8)) - 1;
var prevPage = thisPage.substring(0,8) + prevPageNum;
if (prevPageNum < 0){
break;
}
$('#' + thisPage).removeClass('display').addClass('nodisplay');
$('#' + prevPage).removeClass('nodisplay').addClass('display');
console.log(prevPage);
break;
case 'up':
console.log('up');
break;
}
//$(this).text("You swiped " + direction );
//console.log(this);
}
});
}

Jquery Mobile Listview Autocomplete: how to trigger function when user presses enter?

I’m following the jquery mobile remote autocomplete demo:
http://jquerymobile.com/demos/1.3.0-beta.1/docs/demos/listviews/listview-filter-autocomplete.html
My list is being dynamically populated from my datasource fine and I can do things when the user clicks on a result from the list.
However I also need it to trigger a function when the user hits enter (or clicks “Go” on the phone)... How can I do this? Here's my current code:
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "click","li",function() {
// do stuff when user clicks on item in list
alert('Doing stuff!');
});
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://mywebservice/"+$input.val(),
dataType: "json",
crossDomain: false
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li><a href='#'>" + val.display_name + "</a></li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
I've been searching alot for help, but most results have been talking about the jquery autocomplete and not the jquery mobile listview autocomplete...
Any help would be much appreciated -thanks!
Hey I used a local autocomplete jQM widget but this will work the same for ya -
HTML -
<div data-role="page" id="carPage">
<div data-role="content">
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a car..." data-filter-theme="d">
<li>Acura</li>
<li>Audi</li>
<li>BMW</li>
<li>Cadillac</li>
<li>Ferrari</li>
<li>Honda</li>
</ul>
</div>
</div>
JS -
$(function () {
$('#carPage input[data-type="search"]').on('keydown', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
alert('enter key was pressed');
}
});
});
jsFiddle Demo
/Update
Regarding the go button - Because the autocomplete widget wraps a form element around your content the go button will trigger a submit on the form. This means you can listen to the enter key press and go button press with this simple event handler like this below -
$("#carPage form").submit(function() {
// this will handle both the enter key and go button on device
});
I updated the jsFiddle demo with both approaches above. I like the second approach best because it handles both scenarios the easiest.

Better replacement for ShowModalDialogue

Currently in my website, I am displaying a ShowModalDialogue to display a warning. Recently I have been asked to modify the behavior of this as belows :
Earlier behavior :
I used to just show a warning message. The user can click OK or Close button of the dialogue box to proceed.
New behavior :
I have been asked to insert a text box in the same ShowModalDialogue. Now the user has to insert his initials before clicking OK button. Also now he can not close the dialogue by clicking Close button also. If he tries to close the dialogue by clicking either on Close button or OK button while text box is empty, same pop up has to open with warning. But the trouble is after closing the warning message dialogue is shifted randomly on screen even though its properties have been modified such that it will not move.
Now I have been asked to replace this ShowModalDialogue by something better.
I have two suggestions : 1. CSS div Popup 2. Ajax-control ModalPopup.
Which one of them is better?
Is there anything else which can be used instead that I can use?
My major concerns are good look and easy to handle.
Thanks in advance.
Wanna try qTip2? This one got lots of options for you.
http://craigsworks.com/projects/qtip2/demos/#dialogues
you can simply do it with jquery UI
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": function() {
bValid = $("#d-form").valid();
if (bValid ){
$( "#users tbody" ).append( "<tr>" +
"<td>" + $( "#name" ).val() + "</td>" +
"<td>" + $( "#email" ).val() + "</td>" +
"<td>" + $( "#password" ).val() + "</td>" +
"</tr>" );
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
Fiddle

Categories

Resources