JavaScript First Letter Capitalisation Not Working - javascript

Firstly, this is my first time working with JavaScript so it is probably just me missing something very simple.
All I want to do is get the value of a text box and make an alert with the first letter capitalised. I have everything working, the first letter isn't actually being capitalised.
This is how I am calling the function:
else
{
input = document.getElementById("search").value;
'input'.search();
alert(input);
}
This is the function it self:
function search(string)
{
return string.charAt(0).toUpperCase();
}

this is the correct code
else
{
input = document.getElementById("search").value;
input =search(input);
alert(input);
}

Try this:
input = search(input);
Instead of:
'input'.search();

You aren't changing input at all. Try:
else
{
input = document.getElementById("search").value;
alert(search(input));
}
If you want to permanently change input Try:
else
{
input = document.getElementById("search").value;
input = search(input);
alert(input);
}

A couple of things wrong here,
firstly,
search(input)
instead of
'input'.search()
secondly,
string is immutable so you'll have to do,
input = search(input);
alert(input);
.
.
.
function search(str) {
return (str.replace(str.charAt(0), str.charAt(0).toUpperCase()));
}

Your question is not pretty clear to me, but I assume that you want, if your input string is "hello" , you want the output as "Hello".
Try this
call the method and alert the message:-
alert(search(input));
in the method:-
return Character.toUpperCase(input.charAt(0)) + input.substring(1);

String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase()+this.slice(1);
}
var searchField = document.getElementById("search");
var query = searchField.value;
searchField.value = query.capitalize();
function search(query) {
// query api or something...
}

The answers are correct, but you will have only the first letter in the alert box.
If you don't want only the first letter, here is the solution:
function search(string)
{
return string.substring(0,1).toLocaleUpperCase() + string.substring(1);
}
From https://stackoverflow.com/a/30123193/2379208

Related

Check if value matches mask

I have a input that has a mask of date like __/__/____. I stored it in a variable. Is there a way to detect if it matches the mask properly?
The event is binded on blur, so sometimes it is returning values like 22/12/___.
Is there a way to detect if it definitely fits the scheme with integers and slash only or doesn't?
$('#btn').click(function() {
value = $('#my-input').val() // should be in this format 99/99/9999 and not 12/12/12__
// here I need to check if it is in right format.
if (checkFormat(value)) {
}
}
You can use regex to validate this.
var regex_check = /^\d{2}\/\d{2}\/\d{4}$/ ;
//Edit - Vanilla JavaScript
function foo(date) {
var regex_pattern = /^\d{2}\/\d{2}\/\d{4}$/ ;
var check = new RegExp(regex_pattern);
var res = check.test(date);
// return true or false
return res;
}
Use match() with the following regex : ^\d{2}\/\d{2}\/\d{4}$
your code will be like :
$('#btn').click(function() {
value = $('#my-input').val();
if (value.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
alert("match");
}
else {
alert('the value does not match the regular expression');
}
}

Regex Nan error number only

I have an HTML form with input = "text". I need this to be text and not number.
On the javascript side, I try to remove the nonnumerical character which works only if the first thing I type is a number. If I type a letter first, I will get a NaN error. And yes I need the parseInt as another script launches after this one. Thanks
function numberonly(id)
{
var x = document.getElementById(id);
var numbers = x.value.replace(/[^\d]/g,'');
if (x.value.length>0)
{
x.value = parseInt(numbers, 10);
}
}
If possible, i would avoid using the "event" option as seen here. http://webcheatsheet.com/javascript/disable_enter_key.php
Thanks guys. Problem solved. It was the parseInt giving an error. I think it is parsing what blank means.
SOLUTION:
var x = document.getElementById(id);
var numbers = x.value.replace(/[^\d]/g,'');
if (numbers.length>0)
{
x.value = parseInt(numbers, 10);
}
else
{
x.value = ""; //0 can be used
}

How to validate window.prompt in javascript?

Is there a way to validate the text of the input textBox of the prompt box displayed by calling window.prompt() in javascript?
I mean something like to not to close the prompt box when clicking its OK button if the string written in its input textBox contains numbers or other illegal chars defined by me, etc.
No, there is not.
.prompt is native functionality that can't be modified.
If you want input validation, you're going to need to use a custom prompt. It might be worth looking into UI libraries like jQueryUI, for example.
var obj = {};
function validate( str ){
return !! str; //or your own validation
}
function setName ( error_message ) {
var name = prompt( (error_message || '') + "Enter a name: ");
if ( ! validate( name ) ) {
setName( 'Invalid name entered\n' );
} else {
obj.name = name;
}
}
If you really want to use only prompt then this is the solution. But, I'd suggest you to use a modal dialog or create your own component.
You can't validate the input of a prompt before closing it. You could simulate this by creating your own type of prompt, or using jQueryUI.
I came across this exact problem today while writing a bookmarklet which requests user input.
It struck me that it's possible to validate window.prompt simply by using a while loop:
let promptedAnswer = null;
while (promptedAnswer !== 'spoon') {
promptedAnswer = prompt('Complete this phrase: "There is no [ ]."');
}
Working Example:
let chosenNumber = 0;
while ((chosenNumber < 1) || (chosenNumber > 10)) {
chosenNumber = prompt('Choose a number between 1 and 10:');
}
console.log('Your chosen number is ' + chosenNumber);

Javascript - Detecting the first character and alerting the user

I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.
If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}
Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.
charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);

Javascript replace function won't remove the string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 8 years ago.
I have no idea why this doesn't work, but doing some validation functions and trying to output a dynamic message to an alert when they hit submit and forgot to fill out a field. It works only on the second click of the submit button, as far as removing the string, everything else works when it should.
Here's the code:
var fname = $('#fname');
var lname = $('#lname');
function validatefname(){
var a = fname.val().length;
if(a < 2) {
fname.prev().addClass("error");
if(msg.search("First Name") == -1) {
msg+= "-Please enter your First Name\n";
}
return false;
} else {
fname.prev().removeClass("error");
msg.replace(/Please enter your First Name\n/g, "");
return true;
}
}
fname.blur(validatefname);
fname.keyup(validatefname);
step4submit.click(function(){
if(validatefname()) {
step4form.submit();
return true
} else {
msg+= "\nPlease fill out the fields marked in red";
alert(msg);
msg = "";
return false;
}
});
String.replace returns a new string, rather than editing the string that makes the replace call.
You need
msg = msg.replace( blah )
In JavaScript, Strings are immutable, they can never change. So if you are calling a function to modify a string in some way, that function will return a new string with your changes, rather than modify the original string.
Change the line that is performing the replacement to save the result of the replacement back into the original variable, like so:
msg = msg.replace(/Please enter your First Name\n/g, "");
(there are various performance and safety reasons for this, but that is for another day/another question).
Try changing
msg.replace(/Please enter your First Name\n/g, "");
to
msg = msg.replace(/Please enter your First Name\n/g, "");

Categories

Resources