JavaScript Failing in iWeb - javascript

I am using iWeb for some simple webpage development, and I have put some JavaScript in an HTML widget. The first widget I did worked perfectly, but the second one I am having issues with. The script is supposed to pull the $_GET variables from the URL to address the user. My script worked perfectly outside of iWeb, but fails what I copy it into an iWeb widget. Here is my code:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
//Replace all String Function
String.prototype.replaceAll = function(search, replace){
//if replace is null, return original string otherwise it will
//replace search string with 'undefined'.
if(!replace)
return this;
return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};
//GET from URL
var getVars = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i){
var tmp = args[i].split(/=/);
if(tmp[0] != ""){
getVars[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replaceAll("+", " "));
}
}
$(document).ready(function(){
$("#rsvpName").html(getVars["rsvpName"]);
if( getVars["rsvpResponse"] == "1" )
$("#rvspMessage").html( "You will be attending as part of a party of " + getVars["rsvpNum"] + "." );
else if( getVars["rsvpResponse"] == "0" )
$("#rvspMessage").html("We regret you will not be able to attend!");
alert( getVars["rsvpName"] + getVars["rsvpResponse"] + getVars["rsvpNum"]);
});
</script>
<h1>Thank you, <b><span id="rsvpName">Name</span></b>, for RSVPing.</h1>
<p id="rvspMessage">Message</p>
Anyone have a suggestion?

Related

How do I convert this jQuery codes to JavaScript?

I am having trouble in solving my previous post. I only got a solution which requires jQuery, but I want to use JavaScript instead.
Really need help on this.
Previous Post (For Reference) : HTML - How To Display & Direct Selected Values From Drop Down Menu To A New HTML Page
This is the first jquery codes.
<input type="submit" id="btngo" value="Go" />
<script type="text/javascript">
$(function() {
$("#btngo").bind("click", function() {
var url = "Page2.htm?foodbeverage=" + encodeURIComponent($("#foodbeverage").val()) + "&status=" + encodeURIComponent($("#status").val());
window.location.href = url;
});
});
</script>
This is the second jquery codes.
< script type = "text/javascript" >
var queryString = new Array();
$(function() {
if (queryString["foodbeverage"] != null && queryString["status"] != null) {
var data = "<b>Food Beverages:</b> " + queryString["foodbeverage"] + " <b>Dine Takeaway:</b> " + queryString["status"];
$("#showdata").html(data);
}
}); <
/script>
I've converted the first snippet to a native JS equivalent. I didn't add the status to the URL, it is just more of the same as getting the food beverage.
(function() {
/**
* Handles the click of the submit button.
*/
function onSubmitClicked(event) {
// Get the input element from the DOM.
var beverage = document.getElementById('foodbeverage'),
// Get the value from the element.
beverageValue = beverage.value,
// Construct the URL.
url = 'Page2.html?foodbeverage=' + encodeURIComponent(beverageValue) + '&status=test';
// Instead of going to the URL, log it to the console.
console.log('goto to URL: ', url);
}
// Get the button from the DOM.
var submitButton = document.getElementById('btngo');
// Add an event listener for the click event.
submitButton.addEventListener('click', onSubmitClicked);
})();
<label>
Beverage:
<input type="text" id="foodbeverage"/>
</label>
<input type="submit" id ="btngo" value="Go" />
For the second code snippet, add a div to the form/page. The JS function below will update the div value on window onload with parameters passed. Note that div is only updated if both the querystring paramaters are present.
<div id="showdata"></div>
<script type="text/javascript">
window.onload = passParameters;
//Function to update "showdata" div with URL Querystring parameter values
function passParameters() {
var foodbeverage = getParameterByName("foodbeverage");
var status = getParameterByName("status");
if (foodbeverage != null && status != null) {
var data = "<b>Food Beverages:</b> " + foodbeverage + " <b>Dine Takeaway:</b> " + status;
document.getElementById("showdata").innerHTML = data;
}
}
//Get URL parameter value
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

Combination of word as a autocomplete suggest once that word is selected

I have a paragraph which text I am splitting and creating an array which is later passed to jQuery autocomplete. It's working fine, but what I want is once I select a word and pressed space bar, the next word or (words) to the selected word should be suggested by autocomplete. Is it possible?
This is my current code:
var curDocParaText = $('.docTextFull').text();
var docWords = curDocParaText.replace(/\s{2,}/g, ' ').split(" ");
$( "#parameter" ).autocomplete({
source: function(req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp( "^" + re, "i" );
var a = $.grep( docWords, function(item,index){
return matcher.test(item);
});
responseFn( a );
}
});
This is working but I don't know what to do next to achieve what I want. Any suggestions would be welcome.
You can add any words to the autocomplete suggestion by pushing them to the suggestion array (a in your code). So what you would need to do is:
Check if the last character is a blank space.
If it is, get the last word from the #parameter input.
Search that word in the list of words that you use as source (docWords).
If it is in the source, add the next word to the suggestion.
A simple demo would be something like this (that would be added to your function before the responseFn( a ); part):
// get the value in the input
var textValue = $("#parameter").val();
// if the last character is a space
if (textValue.slice(-1) == " ") {
// get the last word in the sentence
var start = textValue.lastIndexOf(" ", textValue.length-2);
var lastWord = textValue.substring(start + 1, textValue.length-1);
// check if the word is in the source list
var pos = docWords.indexOf(lastWord);
if (lastWord != " " && docWords.length > pos) {
// if it is, suggest the next word too as a sentence
a.push($("#parameter").val() +docWords[pos+1]);
}
}
Notice that this is really basic example, it doesn't check for word duplicates, or case, or anything else. You would need to extend it to make it more "complete" and adjust it to your needs.
Here is a running demo:
var curDocParaText = $('.docTextFull').text();
var docWords = curDocParaText.replace(/\s{2,}/g, ' ').split(" ");
$( "#parameter" ).autocomplete({
source: function(req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp( "^" + re, "i" );
var a = $.grep( docWords, function(item,index){
return matcher.test(item);
});
var textValue = $("#parameter").val();
if (textValue.slice(-1) == " ") {
var start = textValue.lastIndexOf(" ", textValue.length-2);
var lastWord = textValue.substring(start + 1, textValue.length-1);
var pos = docWords.indexOf(lastWord);
if (lastWord != " " && docWords.length > pos) {
a.push($("#parameter").val() +docWords[pos+1]);
}
}
responseFn( a );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<div><b>Demo Sentence:</b></div>
<div class="docTextFull">"The quick brown fox jumps over the lazy dog"</div>
<hr/>
<input type="text" id="parameter">

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

can't get new lines of selected text on IE11

I am trying to replace some text inside a div using a modal window with a form input but for some reason I can't get it to work on IE11. I've realized that it skips new lines when selecting a piece of text containing a <br>
Here is a working example:
http://jsfiddle.net/8VdE9/3/
The funny thing is that I am using the same code in a different page and it gets the new lines fine, which makes me think that I am missing something.
var isIE11 = !!navigator.userAgent.match(/Trident.*rv\:11\./);
range = window.getSelection().getRangeAt(0);
if(!isIE11){
text = new XMLSerializer().serializeToString(range.cloneContents());
}
else{
text = range;
}
text = new String(text);
var textBr = nl2br(text.toString());
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Any help would be very appreciated.
Regards

Get part of the current URL using Javascript

fI'm developing a simple and small search in a Wordpress page using a $_GET variable in the url passed by javascript:
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = document.URL+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
So, the url to search is: MYURL/?page_id=51&pesquisa=test
Of course, the page_id is variable. If I search again, the URL is going to be: MYURL/?page_id=51&pesquisa=test&pesquisa=new, what is wrong.
How could I get just the MYURL/?page_id=51 using javascript? The window.location.pathname is not what I need.
Thanks.
Anything that searches naively will be vulnerable to problems like this: What if the URL is:
http://example.com/?pesquisa=test&page_id=51
You need to search for and remove the relevant query parameter:
var caminho = document.URL.replace(/([?&])pesquisa=[^&]+&?/,"$1")+"&pesquisa="+pesquisar;
Try this hopefully it should work
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = location.protocol + '//' + location.host + location.pathname+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
try this.
var a = document.URL;
var result = a.substr(0, a.indexOf('&'));
Resources:
Get current URL in web browser
how to grab substring before a specified character jquery or javascript
javascript:
<script type="text/javascript">
function get_query_param(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.onload = function() {
if (get_query_param("page_id") != null) {
alert(window.location.pathname + "?page_id=" + get_query_param('page_id'));
}
}
</script>
hope that helps.

Categories

Resources