Hello very smart people of the internet. I have a question that I can't seem to get right. I have three textboxes in a form, which represent 3 different parts of a phone number. Here is the code for them.
<form name="addacell" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
<input type="text" value="" maxlength="3" name="phoneNumber" id="addcell1"/ size="1" placeholder="XXX">
<input type="text" value="" maxlength="3" name="phoneNumber" id="addcell2" size="1"/ placeholder="XXX">
<input type="text" value="" maxlength="4" name="phoneNumber" id="addcell3" size="2" placeholder="XXXX"/>
Next, I am submitting the form and running some validation to check if it meets the phone requirements I have set up for it. (Ignore validation I am not dealing with it until I get everything else straightened out)
<input type="submit" name="submitcell" value="Add" id="submitcell" class="sm-button" onclick="return validatePhone(document.addacell.addcell);"/>
Here is what I need help with: I need to put these 3 individual parts of the phone number together, store it as XXXXXXXXXX in a variable, display it as (XXX)XXX-XXXX and then award you with a huge internet hug.
Thanks in advance for all your hard work for me!!!
First of all: don't name all the separate parts of the phone number the same thing.
Try phone1, phone2 and phone3 in the name attribute of each input.
In your PHP code, something simple as:
$phone1 = $_POST['phone1'];
$phone2 = $_POST['phone2'];
$phone3 = $_POST['phone3'];
// store
$store = $phone1.$phone2.$phone3; // do whatever you want with this
// display
$display = "(".$phone1.")".$phone2."-".$phone3;
Also, there seems to be some misplaced "/" in your code. Check that.
First, rename your inputs. They're all called 'phoneNumber'.
Then call something like $sPhoneNumber = $_POST['phoneNumber1'] . '-' . $_POST['phoneNumber2'] . '-' . $_POST['phoneNumber3'];
The variable $sPhoneNumber now contains the input from the 3 fields (renamed to phoneNumber1, phoneNumber 2 and phoneNumber3).
Using some basic Javascript you can build the strings you are looking for.
var text1 = document.getElementById(addcell1).value;
var text2 = document.getElementById(addcell2).value;
var text3 = document.getElementById(addcell3).value;
var storeText = text1 + text2 + text3;
var displayText = "(" + text1 + ")" + text2 + "-" + text3;
Related
I'm beginner at using JavaScript, and I have read documentation of RegExp and went trough couple of examples but I can't to figure it out how to use it properly.
I have a form which contains 5 input fields. I need to use RegExp to validate user input into form. The forbidden values are
( ) { } ' ! # “ \ /
Other characters are allowed but before submitting a form all input field must be entered (no blank/empty fields are allowed).
Input field id="unos_naziv_proizvoda" must contain at least 5 characters and start with capital letter.
Input field id="unos_opis_proizvoda" must contain at least 3 sentences. Sentence starts with a capital letter and end with a dot.
Input field id="unos_datum_proizvodnje" which is date of manufacturing must be in form of dd.mm.yyyy, can't be in the future (must be lower or same as today) and must be type text
Here is HTML code:
<form id="forma_prijava" class="forma_novi_proizvod" action="http://barka.foi.hr/WebDiP/2016/materijali/zadace/ispis_forme.php" method="POST">
<label for="unos_naziv_proizvoda">Naziv proizvoda</label>
<input type="text" name="naziv_proizvoda[15]" id="unos_naziv_proizvoda" placeholder="Unesite naziv proizvoda" maxlength="15">
<label for="unos_opis_proizvoda">Opis proizvoda</label>
<textarea name="opis_proizvoda" id="unos_opis_proizvoda" placeholder="Ovdje unesite opis proizvoda" rows="50" cols="100"></textarea>
<label for="unos_datum_proizvodnje">Datum proizvodnje</label>
<input type="date" name="datum_proizvodnje" id="unos_datum_proizvodnje">
<label for="unos_vrijeme_proizvodnje">Vrijeme proizvodnje</label>
<input type="time" name="vrijeme_proizvodnje" id="unos_vrijeme_proizvodnje">
<label for="unos_kolicina_proizvodnje">Količina proizvodnje</label>
<input type="number" name="kolicina_proizvodnje" id="unos_kolicina_proizvodnje" placeholder="Unesite količinu proizvodnje" min="1">
<button type="Submit" value="Submit">Dodaj proizvod</button>
<button type="Reset" value="Reset">Poništi unos</button>
</form>
Here is js code:
window.onload = function(){
var provjeri = function(){
var re = new RegExp(/[^(){}'!#"\/]/, g);
var uzorak = document.getElementById("forma_prijava"); //id of a form //
var ok = re.test(uzorak.value);
if(!ok){
alert("Niste unijeli valjani tekst"); //alert message if it's not valid input //
return false;
}
else{
alert("OK"); // message if it's valid input //
return true;
}
};
document.getElementById("forma_prijava").addEventListener("oninput", provjeri);
};
I don't know should I use it on a whole form as one unit or on each input field separately because I have different types of input fields (two are text and others are date, time and number). If someone could provide more understandable explanation when providing an example I would appreciate that. :)
Just to point it out once again, I strictly must use RegExp (pure JavaScript), no other libraries or frameworks do not come in mind!
Thank you in advance!
You can use property pattern of the input Tag
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
my simple html file code
Site Name: <input id="name" type="text" onkeyup="myFunction1(event,this)">
URL : <input id="url" type="text">
javascript code
function myFunction1(event,t){
var nameval= document.getElementById("name").value;
var urlval= document.getElementById("url").value;
var namelen = nameval.length;
var urllen = urlval.length;
var res = nameval.substring(1, namelen);
if(res.length == urllen){
document.getElementById("url").value = t.value;
}
else{
alert("string lengths are not matching");
}
}
what i want to do when user type Site Name in textbox, same text should reflect to URL textbox if name and url text boxes have same text lenghts . but when i speed type site name, my if condition fail after typing few characters and it goes to else block. i dont know why this happening. can anyone help me to improve this code?
Using the onkeyup event isn't your best option for what you are trying to do. You can use the oninput event instead. Here's the modified HTML:
Site Name: <input id="name" type="text" oninput="myFunction1(event,this)">
URL : <input id="url" type="text">
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I better make a list in order to explain the steps that I would like to do:
Get the name of the last element of the html-input (has been generated via PHP)
The basic setting looks like this:
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
Pass it over to a JS function
Append some additional fields (use part of the name as an id for new fields
The JS-script works fine and I am able to add fields. Also the content of the fields is being processed by the PHP script and written in a db.
Short: how do I get the last value, no matter how many fields there are?
edit: I had forgotten that there is a submit button that would appear as the last element as well ... sorry for that
There are a number of approaches, but given all other answers rely on the jQuery library (which adds an unnecessary overhead), I'll focus on showing some plain JavaScript approaches (works on recents browsers above IE8+).
var allTextInputs = document.querySelectorAll('input[type="text"]'),
lastInput = allTextInputs[allTextInputs.length - 1],
lastInputName = lastInput.name;
var allInputsTxt = document.querySelectorAll('input[type="text"]');
var lastInput = allInputsTxt[allInputsTxt.length - 1];
var lastInputName = lastInput.name;
var lastInputValue = lastInput.value;
alert('last input name : ' + lastInputName + '; last input value : ' + lastInputValue);
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
If what you want is the value and not the name attribute, do this after using the same approach as above to get the name of the last <input type="text"/>:
var lastInputValue = lastInput.value;
These approaches will give the value of the last <input /> of the type="text" in the document at the point at which the code is run; to find the value of a last <input /> that's dynamically added to the document, you'll need to re-run a working approach following that element's insertion.
jQuery...
var lastInputName = $('input[type="text"]:last').attr('name');
The following jQuery code should do the trick.
var lastValue = $("input[type=text]:last").val();
Also with jQuery:
var $inputs = $("input[type=text]");
var lastValue = $inputs[$inputs.length - 1].value;
Use CSS3 selectors in combination with sizzle (jquery) to target last element
var name = $('input[name^=E_]:last')[0].name
the last value in PHP or JavaScript?
in PHP the fields are normally passed as an array, so you can get the last value using
end($array)
Even better if you name your filed like this
<input type='text'name='E[8]' value= '123' />
<input type='text'name='E[9]' value= '456' />
<input type='text'name='E[10]' value= '789' />
in JS you need to get the fields into an array and get the last.... you need something like this
var myFields = document.forms["myform"].getElementsByTagName('input'),
var lastValue = myFields[(myFields.length-1)].value;
By wrapping your code a parent element, let's says with an attribute id="inputs", here is a vanilla DOM (no jQuery) solution :
// start by finding the last-most element
var lastInput = document.getElementById('inputs').lastElementChild;
// search backward to the last 'text' element
while (lastInput && lastInput.type !== 'text') {
lastInput = lastInput.previousElementSibling;
}
// and get its value
var lastValue = lastInput ? lastInput.value : null;
The interesting part of this solution is that is create no array, so you save some JavaScript memory.
It should be ok with Firefox, Chrome and IE 9.
I want to get "The walking dead" also but it only gets the first hidden. Can i put a class on .this or how should I do?
$(".articel input[type='button']").click(function(){
var price = $(this).siblings("input[type='hidden']").attr("value");
var quantity = $(this).siblings("input[type='number']").attr("value");
var name = $(this).siblings("input[type='hidden']").attr("value");
var ul = document.getElementById("buylist");
var prod = name + " x " + quantity + " " + price + "$";
var el = document.createElement("li");
el.innerHTML = prod;
ul.appendChild(el);
<form class="articel">
Quantity: <input type="number" style="width:25px;"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30">
<input type="hidden" value="The walking dead">
</form>
The conventional way to identify form fields is by the name property.
HTML:
<input type="hidden" name="title" value="The walking dead">
jQuery:
var name = $(this).siblings('input[name=title]').val();
Your current selector, siblings("input[type='hidden']"), selects all hidden field siblings, but since you have no way to discern them, attr will always just yield the value of the first match.
You could also have iterated over your collection of elements, or accessed them by index siblings('input[type=hidden]:eq(1)') or siblings('input[type=hidden]').eq(1), for instance, but it is a poor design that will break your code if you add another hidden field for something else. You really should prefer to name your elements so that you can access them in a meaningful way and know your data. That way you'll be free to move around and modify your markup according to new requirements, without breaking your script.
By the way, I'm using .val() above, which is shorthand for .attr('value').
One option is to use special selectors, e.g. :first and :last:
var price = $(this).siblings("input[type='hidden']:first").attr("value");
var name = $(this).siblings("input[type='hidden']:last").attr("value");
However, you always can set a class name to the elements:
<input type="hidden" class="price" value="30">
<input type="hidden" class="name" value="The walking dead">
var price = $(this).siblings(".price").attr("value");
var name = $(this).siblings(".name").attr("value");
I would add an class name to your hidden inputs (price, name). This way the html source code is more readable and also the js code will be more readable.
<SCRIPT Language = JavaScript>
function calculate() {
a = 12
b = eval(document.form.number.value)
c = 5J7S
d = (a + b + c)
alert(d)
}
</SCRIPT>
<FORM NAME = form>
Phone: <INPUT TYPE = text SIZE = 3 value ="">
-
<INPUT TYPE = text name = number SIZE = 3 value ="">
-
<INPUT TYPE = text SIZE = 4 value ="">
<P>
<Input Type = Button NAME = b1 VALUE = "Grab Code" onClick = calculate()
</FORM>
5JG7S (Fixed Value)
5+7=12 (Added both numbers from Fixed Value)
Phone number 123-456-7890
4+5+6=15 (Prefix added together)
12+15=27 (Added numbers from the Fixed Value and the numbers that were added from the prefix)
27+5JG7S=275JG7S (Those numbers were added to the beginning of the orginal Fixed Value)
Now this Script that I have:
a is the added numbers from the Fixed Value
b is the input from the form(phone number)
c is the Fixed Value
d is adding each one up so they will display the code as an alert.
Now, if I take out c and just add a and b it performs the addition, if c is in there, it stops the process and produces nothing.
My question is, how do we add the calculated number and append it to the beginning of the fixed value?
Also, the addition works, but not the way I want it to, I want to add the 3 numbers together, the javascript adds 456+12= 468
I know this is very simple code, I am not familiar with Javascript programming and I pretty much pieced together what I found from searching.
I hope this makes sense, if this is not possible I understand.
Thanks!
using parseInt on the values should help with the math. your results are currently inaccurate because the form values are strings: rather than adding numbers you are concatenating strings.
i changed your 'number' input to have an ID attribute, so that you can select with getElementById and replaced the eval call with a call to parseInt.
the value of c in the calculate function needs to be corrected though, not sure what you meant but that will generate an error.
other various HTML tidyness issues (nothing that would break, just easier to read IMHO).
<script type="text/javascript">
function calculate() {
var a = 12;
var b = parseInt(document.getElementById("number").value);
// var c = 5J7S;
var d = (a + b + c);
alert(d);
}
</script>
<form name="form">
Phone: <input type="text" size="3" value=""/>
-
<input type="text" name="number" id="number" size="3" value=""/>
-
<input type="text" size="4" value=""/>
<p>
<input type="button" name="b1" value="Grab Code" onclick="calculate()">
</p>
</form>
hope that helps! cheers.