Failed to execute 'setSelectionRange' on 'HTMLInputElement' - google-chrome

I have the following error an simle "number" input field in Chrome (ver. 33 =>) and other webkit browsers
<input type="number" name="number">
Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input
element's type ('number') does not support selection.
I tested in FF & IE (10=>) and working well
I found the following issue in chromium project:
https://code.google.com/p/chromium/issues/detail?id=346270
any idea?
thank you!

Yes, this is an webkit bug, try this solution:
Jsfiddle demo
Code:
<div class="container">
<form role="form">
<div class="form-group">
<label for="tel">tel</label>
<input type="tel" class="form-control" id="tel" placeholder="tel"/>
</div>
</form>
</div>
<script>
$("#tel").mask("(99) 999-9999");
$("#tel").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});
</script>

Related

How can I create a loop for Chat Bubbles?

I want to develop a loop for chat bubbles. Every time I write a message, a bubble should be created and be on the right. When the chat partner replies, the message should be on the left in the bubble. How can I develop this loop?
My current code is this one:
<div class="Webview">
<div class="message_container" id="myForm"></div>
<form class="send_container">
<input id="textField" type="text">
<p>
<input type="button" id="theButton" value="Nachricht absenden!" onclick="document.getElementById('myForm').innerHTML=document.getElementById('textField').value" />
</p>
<h3>
<div id="div"></div>
</h3>
</form>
</div>
OK, it is not add messages to the DOM in loops, but just add message on Enter on the trigger that sending the message.
If you want to add value from Text Field such as text input,
You probably want to do two steps:
Getting the value from the input
Inject the value into a balloon template (html) and then into the DOM.
Then, you should add Javascript scope into your html or just include js file that contain the following function:
function addMessage() {
// Add XSS validation
const $messages = document.getElementById('myForm');
const $textElement = document.getElementById('textField');
const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
$messages.innerHTML += newMessage;
return false;
}
<input type="button" id="theButton" value="Nachricht absenden!" onclick="addMessage()" />
In jQuery it will be like this (in the js scope of course):
$("#theButton").off('click').on('click', function() {
e.preventDefault();
const $messages = $('#myForm');
const $textElement = $('#textField');
const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
$messages.html += newMessage;
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="theButton" value="Nachricht absenden!" />
Hope it helps :)
Good luck

Basic API with HTML: Creating Objects

I have a pretty simple calculator that I am trying to setup.
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit">
</form>
The next step is I need to pull the top 20 (quantity) cryptocurrencies, then divide the 500 (dollars) between them relative to market cap.
Here's the API website: https://coinmarketcap.com/api/
Clicking on https://api.coinmarketcap.com/v1/ticker/?limit=10 shows me the top 10 currencies.
How can I ADD up all the market caps of each individual currency on the page. Then create ratios from them?
Math part is pretty straightforward, what I don't get is how to actually pull the data from the API link and get it in a workable format.
Lookup Jquery and Ajax:
You can implement this like this:
function getCurrencies()
{
$.ajax(
{url:"https://api.coinmarketcap.com/v1/ticker/?limit=20",
success:function(data) {
//console.log(data);
var totalcap=0.0;
var u=$("<ul>");
for(var i=0;i<data.length;i++) {
var currency=data[i];
var cap=parseFloat(currency["market_cap_usd"]);
var li=$("<li />").html(currency["name"] + " " + cap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
u.append(li);
totalcap+=cap;
}
$('#currlist').html('').append(u);
$('#cap').html(totalcap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
$('#data').val(JSON.stringify(data));
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"}
);
}
textarea {width:600px;height:250px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit" onclick="getCurrencies(); return false"
>
Total Market Cap:<div id="cap"></div><br />
Currencies: <div id="currlist"></div><br />
<textarea id="data"></textarea>
</form>

Format input field "time" to not show seconds and milliseconds

in AngularJS 1.5 I have a form with an input field of type "time". It works, but the time shown should be HH:mm - without seconds, etc.
Chrome does this by default, but Firefox and Internet Explorer show with seconds and milliseconds (e.g. "14:56:00.000" instead of "14:56").
How can we show the required time format in all browsers?
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-time-input-directive-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="timeExample">
<script>
angular.module('timeExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(1970, 0, 1, 14, 56)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a time between 8am and 5pm:</label>
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm" min="08:00" max="17:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.time">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</body>
</html>
Thank you!
Firefox and IE don't support <input type="time">, it's browser dependent. See this link for more info on W3. So your input field will not be able to display it the same way as in Chrome.
An alternative is to use uib-timepickerfrom angular-ui or try one from jquery like webshim.
try using step attribute and set it to 60".
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm" min="08:00" max="17:00" required step="60" />
Date time input types are not supported by IE11 and Safari. But we hope for the best and regularly visit this "can_i_use" link to see if something has changed.
https://caniuse.com/#feat=input-datetime
We can write a common method in controller end to not allow second and millisecond to be shown in input type time
getFormatDate = function (val) { // assuming val is date like "/Date(946673340000)/"
if (val != undefined) {
date = new Date(val.match(/\d+/)[0] * 1); // creating a date object from val
return new Date(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes());
}
}

Why are my inputs not resetting?

The below code generates several forms depending on data returned from the server. Everything generates fine, but after clicking on an AnswerOpenQuestion button the input does not clear/reset. What's going on here?
angularJs code:
var availableInterviewController = function($scope, $http) {
// define initial model
$scope.interviews = [];
// retrieve available interviews
$http.get('/api/UserInterviewsApi/AvailableInterviews')
.success(function(data) {
// update interviews
$scope.interviews = [];
$scope.interviews = data;
});
// define open question answer selection
$scope.Answer = "";
// define multiple choice selection
$scope.selectedChoice = "";
// define answer open question button
$scope.AnswerOpenQuestion = function() {
$scope.Answer = ans;
alert(q.Question + ' and ' + $scope.Answer);
$scope.Answer = ''; // <---This is not clearing/resetting the HTML form inputs
};
// define answer multiple choice button
$scope.AnswerMultipleChoice = function() {
//
};
};
// assign the new controller to the main angular app
myAngApp.controller('availableInterviewCtrl', availableInterviewController);
Html code:
<form class="form-group" ng-repeat="q in inter.Questions">
<fieldset style="display: inline-block;">
<legend>Question {{$index + 1}}</legend>
<!--Open Ended-->
<div class="form-group" ng-show="q.MultipleChoices.length === 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong><br />
</label>
<input name="openQuestion" id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="Answer" />
<button ng-click="AnswerOpenQuestion()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
<!--Multiple Choice Question-->
<div class="form-group" ng-show="q.MultipleChoices.length > 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong>
</label>
<div>
Select an answer:
<label ng-repeat="x in q.MultipleChoices">
<input name="currentChoice" type="radio" value="{{x.Id}}"
ng-model="selectedChoice" />
{{x.Choice}}
</label>
<button ng-click="AnswerMultipleChoice()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
</div>
</fieldset>
</form>
UPDATE - Solution
AngularJs:
// define open question answer selection
$scope.OpenAnswer = { Answer: '' };
// define answer open question button
$scope.AnswerOpenQuestion = function (q, ans) {
$scope.OpenAnswer.Answer = ans;
alert(q.Question + ' and ' + $scope.OpenAnswer.Answer);
// clear the input
$scope.OpenAnswer.Answer = '';
};
Html:
<input id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="OpenAnswer.Answer" />
Don't use the scope as a model instead make an object that wraps the data model and assign it to a property of the scope.
$scope.myModel = {Answer:''}
Also don't use value in most cases ngmodel is all you need for two way binding.
In js strings are immutable so the original reference is not being updated instead a new string is being made, the digest cycle won't see this as a change to the original string.

How do preserve leading and trailing whitespace when using an input tag?

I am playing with Angular and writing a Regex tester.
Problem is leading whitespace is trimmed when I enter data. See example jsfiddle here:
So when the page loads I have the RegEx "^\d+$".test(" 123 ") which results in "No Match", But if you enter an extra leading or trailing space in the Candidate box:
The leading and trailing spaces are removed from my variable
The result changes "Match"
Here is my HTML:
<div id='ng:app' class='ng-app: myApp' ng-app='myApp'>
<div ng-controller="Controller">{{addTodo2()}}
<form novalidate class="simple-form">Pattern:
<input type="text" ng-model="pattern" />Candidate:
<input type="text" ng-model="candidate" />
<br />.{{candidate}}.
<br>.{{candidate2}}.</form>
</div>
</div>
And here is the associated JavaScript:
function Controller($scope) {
$scope.pattern = "^\\d+$";
$scope.candidate = " 123 ";
$scope.candidate2 = " 123 ";
$scope.addTodo2 = function () {
var str = "Javascript is an interesting scripting language";
var re = new RegExp($scope.pattern, "g");
var result = re.test($scope.candidate);
if (result) {
return "Match22";
} else {
return "No Match22";
};
};
}
var myapp = angular.module('myApp', []);
Updated the fiddle, added ng-trim="false" to the input tags
http://jsfiddle.net/T2zuV/12/
<div id='ng:app' class='ng-app: myApp' ng-app='myApp'>
<div ng-controller="Controller">{{addTodo2()}}
<form novalidate class="simple-form">Pattern:
<input type="text" ng-model="pattern" ng-trim="false"/>Candidate:
<input type="text" ng-model="candidate" ng-trim="false"/>
<br />.{{candidate}}.
<br>.{{candidate2}}.</form>
</div>
</div>