• 0

[Javascript] Combine 2 form fields into one.


Question

I've got a credit card form and on submission it requires that the expiry date is submitted from a single string as mmyy. Instead, the form is mm and yy in separate submission boxes.

I figured it would be possible to take the two value's and combine them by sitcking them into a hidden field.

I found a script online and due to my very limited knowledge of javascript I wouldn't actually know what to do with this and it looks looks somewhat incomplete:

  Quote

<script language=javascript>

funtion populate(){

Fname = document.form1.FirstName.value;

Lname = document.form1.LastName.value;

document.form1.CONTACT.value = Fname + " " + Lname;

}

</Script>

Then call the function with onchange on your lastname field <input ID="LastName" value="" onChange="populate()"

I'm completely full of cold at the moment so my brains not firing on all thrusters.

Would this require any library like jquery to work?

If there's a way to do this without javascript that would be even better. Thing is as the forms being submitted via a thirdparty api I don't have the luxury of combining them via PHP at form submission.

Appreciate any help.

Many thanks.

Alex

8 answers to this question

Recommended Posts

  • 0

No, it's simple.

<script type="text/javascript">
function join_ym()
{
var yy = document.getElementById('yy').value;
var mm = document.getElementById('mm').value;
document.getElementById('joint').value = yy+mm;
alert(document.getElementById('joint').value);
}
</script>

<input type="text" id="yy" />
<input type="text" id="mm" />
<input type="hidden" id="joint">
<input type="button" value="Join!" onclick="join_ym();">[/CODE]

Edit:

Time to explain. First we have a form with an id called 'yy'. We get its value through the [b]document.getElementById('id_name').value[/b] javascript function. Replace id_name with the id of the text input.

We do the same for mm. We get its value through the document.getElementById('mm').value, whereas mm is the text input's id.

We then assign the value to the hidden form, which I called [u][b]joint [/b][/u] through the same procedure as I took the other two's (mm and yy) value.

We do this again with the [b]document.getElementById('joint').value = [/b]function and operator, whereas joint is the id of hidden form.

For concatenating strings, I used the [b]+[/b] operator. Which joined the yy and mm variables together, forming a new string.

At the end, I used alert, to throw at screen what is the value of [b]joint, [/b]my hidden form.

I hope I've been clear, anything else just ask.

Edit #2. Since you seem to have PHP knowledge, the [b]+[/b] operator is analog to the [b].[/b] (dot) in PHP

  • 0

Thanks for this! I'm not at home right now so will implement this in the morning.

Would adding the function to the onclick operator on the submit button ensure that the appropriate hidden field was populated prior to the form being submitted? Or would it be best to have the relevant field updated as and when those fields are filled out?

Again, many thanks!

  • 0

Here you go:


<html>
<head>
</head>
<body>
<form action="" method="get">
<input type="text" name="name_first" placeholder="First Name" oninput="join_names();" onpaste="join_names();" /><br />
<input type="text" name="name_last" placeholder="Last Name" oninput="join_names();" onpaste="join_names();" /><br />
<input type="text" name="name_full" placeholder="Full Name" /><br />
<input type="submit" onclick="join_names();" />
</form>
<script type="text/javascript">
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+' '+string_two;
}
else {
return string_one+string_two;
}
}
function join_names() {
var input_name_first = document.getElementsByName('name_first')[0].value;
var input_name_last = document.getElementsByName('name_last')[0].value;
var input_name_full = document.getElementsByName('name_full')[0];
var var_name_full = concatenate(input_name_first, input_name_last, true);
input_name_full.value = var_name_full;
}
</script>
</body>
</html>
[/CODE]

This will not only update the code with every key they press, but also eliminates the need for ids for your elements if you don't want them. This works solely off of the name attribute of your inputs which is a bit cleaner and more useful if you are styling your inputs similarly (using classes instead of ids). Also, I added the ability to concatenate the strings with or without a space, and made it cross browser compatible. Hopefully you find this useful!

Also, if you plan on using a textarea, change the oninput attribute to textInput. :)

  • 0

Thanks fellas.

I combined elements from both methods to a nice simple scripts which seemingly does what I wanted. I based it mostly off Jose_49's method because it seemed simpler for me to achieve but if I've overlooked something please let me know:

&lt;input id="expiry" type="hidden" name="field18317078" value="" /&gt;


&lt;input id="month" class="tiny" placeholder="mm" type="text" oninput="join_expiry();" onpaste="join_expiry();"&gt;
&lt;input id="year" class="tiny" placeholder="yy" type="text" oninput="join_expiry();" onpaste="join_expiry();"&gt;


&lt;script type="text/javascript"&gt;
function join_expiry()
{
var mm = document.getElementById('month').value;
var yy = document.getElementById('year').value;
document.getElementById('expiry').value = mm+yy;
}
&lt;/script&gt;

  • 0
  On 29/01/2013 at 11:10, Axel said:

Thanks fellas.

I combined elements from both methods to a nice simple scripts which seemingly does what I wanted. I based it mostly off Jose_49's method because it seemed simpler for me to achieve but if I've overlooked something please let me know:

&lt;input id="expiry" type="hidden" name="field18317078" value="" /&gt;


&lt;input id="month" class="tiny" placeholder="mm" type="text" oninput="join_expiry();" onpaste="join_expiry();"&gt;
&lt;input id="year" class="tiny" placeholder="yy" type="text" oninput="join_expiry();" onpaste="join_expiry();"&gt;


&lt;script type="text/javascript"&gt;
function join_expiry()
{
var mm = document.getElementById('month').value;
var yy = document.getElementById('year').value;
document.getElementById('expiry').value = mm+yy;
}
&lt;/script&gt;

No probs.

Be careful with the oninput, placeholder methods. They are HTML5 and only modern browsers support it.

  • Like 2
  • 0
  On 29/01/2013 at 11:52, Jose_49 said:

No probs.

Be careful with the oninput, placeholder methods. They are HTML5 and only modern browsers support it.

  On 29/01/2013 at 12:28, Axel said:

So I suppose it's best to add the function on submit too? Would "onclick" work with older browsers?

Well, the onpaste (which is not html5) has support accross IE, Firefox, Safari, and Chrome. The oninput is a more up-to-date method, and also adds support for Opera. By combining them, it is very unlikely that you will have any issues at all.

Thanks for pointing that out though. :)

  • 0

I have to say... THANK YOU!!!!!! Awesome how it worked like a charm to me! really THANK YOU!!!!!!!! i have implemented this into RsForm Pro with joomla! with a little variation to fit my forms.

My case was:
Create a user name field (one field of the form) based on two form field filled by the user, with a special caracter dividing the two captured field forms data.
Apart, the JS to do the trick of join two field into one, will be ran only if the user select to create the account selecting a checkbox field and if not nothign will be done.

<script type="text/javascript">
function copy(){
  //This is the check box option where i want if selected, the data to be copied to the form field "test"
if (document.getElementById("copy0").checked==true)
    
    {
var cupon = document.getElementById('cupon').value;
var celular = document.getElementById('celular').value;
//Agregue un signo '-' al resultado compilado y agregue un signo + al segundo valor.
document.getElementById('test').value = cupon+'-'+celular;
alert(document.getElementById('test').value);
    }
    //my checkbox got two options. So first one is "copy0" second one is "copy1" and if they choose secondone, no copy will be done.
    else if (document.getElementById("copy1").checked==true)
    
    {
    document.getElementById("cupon").value="";
    document.getElementById("celular").value="";
    }
    
}
</script>

XHTML 
<fieldset class="formFieldset">
<legend>{global:formtitle}</legend>
{error}
<!-- Do not remove this ID -->
<ol class="formContainer" id="Trend_{global:formid}_page_0">
	<li class="block-cupon">
		<div class="formCaption">{cupon:caption}<strong class="formRequired">(*)</strong></div>
		<div class="formBody">{cupon:body}<span class="formClr">{cupon:validation}</span></div>
		<div class="formDescription">{cupon:description}</div>
	</li>
	<li class="block-descphone">
		<div class="formCaption">{DescPhone:caption}</div>
		<div class="formBody">{DescPhone:body}<span class="formClr">{DescPhone:validation}</span></div>
		<div class="formDescription">{DescPhone:description}</div>
	</li>
	<li class="block-celular">
		<div class="formCaption">{celular:caption}<strong class="formRequired">(*)</strong></div>
		<div class="formBody">{celular:body}<span class="formClr">{celular:validation}</span></div>
		<div class="formDescription">{celular:description}</div>
	</li>
	<li class="block-email">
		<div class="formCaption">{email:caption}<strong class="formRequired">(*)</strong></div>
		<div class="formBody">{email:body}<span class="formClr">{email:validation}</span></div>
		<div class="formDescription">{email:description}</div>
	</li>
	<li class="block-test">
		<div class="formCaption">{test:caption}</div>
		<div class="formBody">{test:body}<span class="formClr">{test:validation}</span></div>
		<div class="formDescription">{test:description}</div>
	</li>
	<li class="block-copy">
		<div class="formCaption">{copy:caption}<strong class="formRequired">(*)</strong></div>
		<div class="formBody">{copy:body}<span class="formClr">{copy:validation}</span></div>
		<div class="formDescription">{copy:description}</div>
	</li>


</ol>
</fieldset>

Really thank you so much dude @Jose_49!

  Quote

what tipe of course do you suggest to learn more about this? Jose_49

Expand  

 

Edited by DavidDem
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft announces multi-year partnership with AMD for future of Xbox consoles and hardware by Pulasthi Ariyasinghe The Xbox Games Showcase was earlier this month with its own hardware announcement, but Microsoft had kept a major partnership under wraps for now. Today, it revealed that it has established a "strategic multi-year partnership with AMD" to develop its next-generation Xbox consoles and other devices. In a video uploaded to the Xbox social channels, Xbox president Sarah Bond announced the partnership with AMD. Remember that Microsoft's Xbox Series X|S consoles and the previous Xbox One lineup already tout AMD silicon inside, so the continued partnership isn't a big surprise. "Together with AMD we're advancing the state of art in gaming silicon to deliver the next generation of graphics innovation to unlock a deeper level of visual quality and immersive gameplay and player experiences enhanced with the power of AI, all while maintaining compatibility with your existing library of Xbox games," said Bond in the video promoting the partnership. The two Xbox Ally Windows gaming handhelds that were announced earlier this month also come with AMD internals, offering handheld gaming experiences with a unique, lightweight version of bloat-free Windows 11. What was interesting were the few hints that were dropped regarding the focus of the Xbox brand going forward. "This is all about building you a gaming platform that's always with you, so you can play the games you want across devices anywhere you want, delivering you an Xbox experience not locked to a single store or tied to one device," added Bond. It was also confirmed that the next generation of Xbox devices will continue to offer backward compatibility, letting players keep their existing libraries when moving forward. Finishing off the video, Bond confirmed that the Xbox team is now working on Windows to make it the "number one platform for gaming," perhaps alluding to moving away from being focused on home consoles.
    • Kudos to the happy talented people who created that happy trailer.
    • Maybe the site will get out of dabbing into Identity Politics.
    • ASUS TUF Gaming A16 (2024): A capable gaming laptop with AI for $300 less by Paul Hill If you are in the market for a mid-range gaming laptop packed with AI features, check out the ASUS TUF Gaming A16 2024 laptop, which is now discounted by 19% to just $1,299. The list price of this laptop is $1,599.99, so you’re saving $300 by taking advantage of this deal. Inside are the AMD Ryzen AI 9 HX 370 processor, which supports Windows AI features such as Recall, and the Nvidia GeForce RTX 4060 GPU, which offers solid gaming performance at 1080p. What you get: Features and performance for gamers The ASUS TUF A16 includes a 16-inch display with a 16:10 aspect ratio. Its refresh rate is 165Hz to minimize lag, it supports Nvidia G-Sync, and it has a 2.5K resolution. Inside the device, we have the AMD Ryzen AI 9 HX 370 processor, Nvidia GeForce RTX 4060 GPU, 16GB of LPDDR5X RAM, and a 1TB PCIe Gen 4.0 SSD. A nice thing ASUS has taken into consideration with this laptop is durability. It is MIL-STD-810H certified, meaning it has passed durability tests. While the laptop is discounted, it’s not cheap, so knowing it’s durable is a plus. In terms of cooling, it features Arc Flow Fans, four exhaust vents, five head pipes, and an anti-dust filter. Combined, these will keep the laptop running cool, providing better gaming performance. As for sound, the A16 features Dolby Atmos, Hi-Res Audio, and two-way AI noise cancellation. All of this will make your gaming sessions more immersive, and the noise cancellation will ensure you can hear your teammate properly. The laptop runs Windows 11 and includes 3 months of PC Game Pass, so you can play games right away, and save some money given the rising cost of games. Who should buy this laptop? Buyers can expect solid performance from this laptop for its price point. With the fast SSD, AI-capable CPU, and decent graphics card, you can expect to get most school or work tasks done easily, and it should capably handle games up to 1080p. The cooling features are nice because they will prevent any performance degradation, and the MIL-STD-810H rating offers peace of mind related to durability. If you are seeking the cutting edge of gaming performance, this laptop may not be for you. Additionally, if you aren’t much of a gamer or a creator, this laptop could be overkill, and you’d get away with buying something cheaper. If you want to pick it up, check out the buying link below. ASUS TUF Gaming A16: $1,299 (Amazon US) / MSRP $1,599.99 This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • After Elon has been high as a kite IN the oval office on video, I don't think anyone can mention Hunter and it mean anything anymore. As far as I'm concerned, Elon wiped the Hunter laptop issue away. And Marge Traitor Green just used that laptop to show congress Hunter naked so that she could look at him more! That was horrible.
  • Recent Achievements

    • Reacting Well
      Cole Multipass earned a badge
      Reacting Well
    • Reacting Well
      JLP earned a badge
      Reacting Well
    • Week One Done
      Rhydderch earned a badge
      Week One Done
    • Experienced
      dismuter went up a rank
      Experienced
    • One Month Later
      mevinyavin earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      696
    2. 2
      ATLien_0
      275
    3. 3
      Michael Scrip
      218
    4. 4
      +FloatingFatMan
      188
    5. 5
      Steven P.
      146
  • Tell a friend

    Love Neowin? Tell a friend!