How to Format Pre-populated Input Fields - javascript

I am populating a telephone input field with data from an API call when the page loads.
I have a function that formats phone numbers to look like this: +1 (888) 333 4444. But the function is only working when there is a keyup event. I am trying to get this pre-populated input value to be formatted with this same function. I've tried changing the event from keyup to load, onload, but it has no affect. I tried wrapping the function in a setTimeout delay, but that didn't work either.
I know I'm missing something simple...
<!DOCTYPE html>
<html>
<body>
<form>
<label>Telephone</label>
<input type="tel" onload="phoneMask()" value="<?= data.phone ?>"/>
</form>
<script>
//Format telephone numbers
function phoneMask() {
var num = $(this).val().replace(/\D/g,'');
$(this).val('+' + num.substring(0,1) + ' (' + num.substring(1,4) + ') ' + num.substring(4,7) + ' ' + num.substring(7,18));
};
$('[type="tel"]').keyup(phoneMask)
</script>
</body>
</html>

At the bottom of the page, in the script section add this:
function phoneMask() {
var num = $("input[type=tel]").val().replace(/\D/g,'');
$("input[type=tel]").val('+' + num.substring(0,1) + ' (' + num.substring(1,4) + ') ' + num.substring(4,7) + ' ' + num.substring(7,18));
};
$(document).ready(function() {
phoneMask();
} );
I have edited your phoneMask function.
This will call your phoneMask function once the page has loaded.
This works on the assumption that there is only going to be one box of type tel. Otherwise you will need to wrap the code in phoneMask areound an each with the selector using each.

Related

How to display record update data until next event in javascript ajax function?

After submit input data loaded successfully in back-end server, however needed help to display "Added: id of the Country" right below submit button after success POST method that stays for few sec until server datapull function is called. POST method is success and was able to load and display data however having hard time to display success note for few sec along with retrieve data from datapull function
added below line inside ajax complete function assuming POST was success and run below line after complete
$('#optional').append('Added :' + state.id + ' of the ' + state.ctry).show(5000);},
HTML code
<!DOCTYPE html>
<html>
<head>
<title>State Sq Mile</title>
<script type = "text/javascript"
src = "http://code.jquery.com/jquery-latest.min.js">
</script>
</head>
<body>
<form>
Country: <input type="text" id="ctry" name="city"><br>
State: <input type="text" id="state" name="state"><br>
Area: <input type="text" id="area" name="area"><br>
<button id="addValue">Submit</button>
</form>
<p id='optional'></p>
<ul id = 'entry'></ul>
<script type = "text/javascript" src="sample.js"></script>
</body>
</html>
sample.js
(there are addition data pull code which i havent included)
$.ajax({
url: urlpost,
type: 'POST',
data: {"Country":"ctry","State":"state","Area":"area"},
success: function(state){
$('#entry').append('<li>' + state.ctry + ': ' + state.state + ': ' + state.area + '</li>');
error: function(state){console.log(state);},
complete: function () {
$('#optional').append('Added :' + state.id + ' of the ' + state.ctry).show(5000);},
setTimeout(function() { datapull()}, 6000)}
});
Expected HTML page output
Country: <html input text>
State: <html input text>
Area: <html input text>
Submit <Button>
Added: id of the Country
• USA: Texas : 268,596.46 sq mile
• USA: California: 163,696.32 sq mile
Your problem description could be a little bit more detailed. However I tried to work with what I have.
My idea is to add inside success: function() {... an exterior function call like this:
Inside we do 2 things, we append a paragraph with a message and we trigger another function that will be executed after timeToHide amount of time ( 3000ms in the example )
function displayMessage(target, content, timeToHide) {
$(target).append('<p class="message">' + content + '</p>')
return setTimeout(function() {
$('.message').remove()
}, timeToHide)
}
success: function(state){
$('#entry').append('<li>' + state.ctry + ': ' + state.state + ': ' + state.area + '</li>'
displayMessage($('.target', 'Succcess!', 3000))
);
Here is a simple JSfiddle that should help: https://jsfiddle.net/mkbctrlll/bc60t92e/25/

Why jQuery append() removes words after first blank space in string

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

Jquery Mobile dynamic created range change event not firing

I'm creating a Jquery Mobile range dynamic with this code:
$('<input data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
Now I want to add a change event with this code:
$(".brightness").change(function() {
alert("changed");
});
I have no idea why it's not working, I tried to refresh the range after defining the event, I tried to bind the event to the range, nothing works. The function that contains the first code snippet, is getting called first, and the function that contains the second snipped is getting called second.
Does someone of you know what I'm doing wrong, or what I'm overlooking?
Two things you need to do
1. add css class brightness to your range input
$('<input class="brightness" data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
Add event handler using on
$(document).on("change",".brightness",function() {
alert("changed");
});
EDIT - for id selector use # instead of .(dot) like below
$(document).on("change","#brightness",function() {
alert("changed");
});
Check jQuery Selector
Use on method for your dynamically created elements
$(".brightness").on('change',function() {
alert("changed");
});
I think you are giving id brightness and Calling Onchange Event by Class using dot(.).
if the name of the id is brightness then
you should use #
$("#brightness").on('change',function() {
alert("changed");
});
but if you want call onchange event by class only then you need to add class to your input and use dot(.)
$('<input class="brightness" data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
$(".brightness").on('change',function() {
alert("changed");
});

Accessing Wikipedia API with JSONP

I've been trying for the last few days to make my code work, but I just can't find the problem.
I want to make communication with the Wikipedia server and get their JSON API so I can make a list of items corresponding to the input value of searchInput.
I've been looking into JSONP, finding in the end that I can add "&callback=?" to my API request and that it should work.
Now, even though I've added it, the communication still isn't happening.
I've noticed that the console on codepen.io returns "untitled" for a moment while initializing the code after processing the "#searchInput" input.
Perhaps the problem is in my for...in loop.
Do you have any idea what I should do?
The link to my code: http://codepen.io/nedsalk/pen/zqbqgW?editors=1010
(JQuery is already enabled in the "settings" menu)
If you prefer the .html edition of the code:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Object Oriented JavaScript </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"> </script>
</head>
<body>
<h1> Wikipedia viewer </h1>
Go random!
<form>
<input type="text" name="searchInput" id="searchInput" placeholder="Search Wikipedia"
onkeydown = "if (event.keyCode == 13)
document.getElementById('submit-button').click()"/>
<input type="submit" id="submit-button"/>
</form>
<div id="list"></div>
<script>
$(document).ready(function() {
$("#submit-button").on("click",function (){
var input=$("#searchInput").val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?',
function(API){
$("#list").empty();
for (var id in API.query.pages)
{if(API.query.pages.hasOwnProperty(id){
$("#list").html('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">'
+'<div id="searchList">'
+ "<h2>" + id.title + "</h2>"
+ "<br>"
+ "<h3>" + id.extract + "</h3>"
+ "</div></a><br>")
}}
})
})
})
</script>
</body>
</html>
You have several issues in your code:
you should hook to the submit event of the form, not the click of the button, and use event.preventDefault() to stop the submission.
you loop through the keys of the returned object and attempt to access properties of those strings, instead of using the keys to access the underlying properties.
you set the html() in each loop, so only the final item will be visible. You should use append() instead.
Try this:
$("form").on("submit", function(e) {
e.preventDefault();
var input = $("#searchInput").val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?', function(response) {
var pages = response.query.pages;
$("#list").empty();
for (var id in pages) {
$("#list").append('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">' +
'<div id="searchList">' +
"<h2>" + pages[id].title + "</h2>" +
"<br>" +
"<h3>" + pages[id].extract + "</h3>" +
"</div></a><br>")
}
});
});
Working example

Textarea value remain the same after submitting a form

My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable

Categories

Resources