• 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:

<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

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

No probs.

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

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

 

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

    • No registered users viewing this page.
  • Posts

    • Write to your MP 😄 Like believing in Santa. Total surveillance IS the goal. Wake up.
    • This whole dumb age verification thing needs to die and be replaced by giving parents tools to control devices. Why am I required to plaster my ID all over the internet to prove I'm old enough when parents should be the ones dictating what their kids are doing on their phones. Apple released great set of tools for iPhones coming to iOS 27 that do just that. Why are governments not mandating that kind of control to phone makers to built them into phones. This whole thing is so absolutely idiotic it's wild.
    • Remeber this decade, when the free internet died... tell your grand kids about this, record there reaction and post it on InstaTwitBook.com
    • UK nudity blockers are a looming privacy disaster, we must be able to see the source code by Paul Hill Image via Pexels The UK government, just like many state governments in the US and national governments around the world, has begun going on a bit of a power trip when it comes to digital safety. The major step taken so far is the introduction of the Online Safety Act, which requires users to prove their age to access adult websites (it includes more than this, too). Now, UK PM Keir Starmer is calling on Apple and Google, and presumably other mobile OS makers, to scan phones for explicit images to protect children. This potentially mandatory on-device scanning by vendor-controlled software will create unacceptable harms to individual freedoms and transparency, and introduce massive surveillance risks. In a statement on June 8, the Prime Minister stated that big tech companies, such as Apple and Google, must add features to their platforms, such as iOS and Android, that will detect and block sexually explicit or nude images involving under-18s on phones or tablets. Adults who want to take or send nudes would be required to hand over some form of identification to stop their phone from blocking these pictures, creating unnecessary privacy risks. According to the government, it wants to see these measures implemented within three months; otherwise, the government will introduce legislation to force them to introduce such technology. The legislation will include fines for companies and maybe even criminal liability for tech bosses who do not comply with the measures. In its announcement, the government said that stopping users from taking, sending, or receiving nudes without verifying their age is technically feasible, and pointed to a British firm called SafeToNet, which has made proprietary, closed-source, uninstallable software called HarmBlock and is actively selling a device with it enabled and is working with other OEMs. The fact that this software is closed source is a huge problem because it’s a black box; you do not know what it is doing on your device. The fact that it is unremovable is also a problem because you lose control of a phone that you own. Laughably, the government, just before highlighting SafeToNet, says that companies must introduce such measures “without threatening privacy or collecting any data.” It then says over-18s will still be able to view adult content by providing proof of age… Which sounds to me like data collection. SafeToNet makes some debatable claims about HarmBlock The government’s example software, HarmBlock, is a hugely alarming choice to espouse the virtues of this type of software. SafeToNet claims that HarmBlock is “ethically developed,” but this is the opposite of the truth. This black box software puts digital handcuffs on you if it’s installed in your device, taking away your freedom to control what software runs on your device, as it cannot be removed. It is not even free software, so we cannot inspect the source code to see what it is doing. For all we know, it could be acting maliciously. While that’s unlikely, we can’t verify that it’s not doing that. When Google and Apple do inevitably integrate these features on devices in the UK, they are very likely to be closed-source binaries, which will also be non-auditable. They will also have identity services built into them, which will require at least temporary collection of sensitive identity documents to verify your age. One saving grace for Android users is that this nudity blocker will very likely be implemented within the Google Play infrastructure that’s deeply tied into commercial Android devices. However, anyone with enough determination to throw out Google apps from their phone by flashing a custom ROM could find they regain control over their phone again without these digital handcuffs. Obviously, this is only how I expect Google to implement the feature; if it bakes it into the open-source Android somehow, that would be bad news for anyone looking to escape it. Outside of stripping mobile phone users of their freedom and sovereignty over their devices, these proprietary on-device machine learning or hash-matching solutions cannot be independently audited. This means that hackers could potentially exploit them because security researchers can’t investigate the code, and they could overstep their intended use case and collect even more user data without anybody knowing. We also wouldn’t know if the code is prone to detecting false positives or biased classification, because we can’t see the code. In the government’s announcement, contributing comments from the Internet Watch Foundation keep talking about “on-device protections” as if to say that users don’t need to worry about server-side processing; however, this is misleading, as data could flow from devices for the purpose of updates, remote model changes, telemetry, or server-side matching. We’ve also seen with the Online Safety Act that the government is never content with the laws it introduces; it always wants to expand the controls. If this scanning functionality arrives on devices, it might only block nudes initially, but later governments could pressure vendors for expanded access or use mandated features for other surveillance aims. The introduction of on-device scanners opens the door to massive risks in the future. Once nude blocking becomes normalized, regulators like Ofcom or politicians themselves could push for more controls over people’s devices. Very possible candidates for blocking include hate speech, misinformation, or undesirable political content. Also, there is a chance that once Apple and Google have developed this software, they might attempt to reuse the infrastructure for commercial or foreign requests, putting customers in greater danger. Just the UK's demand for this sets a precedent. What if a dictatorship decides to spy on activists by demanding that Google or Apple implement similar controls? Another concern with this scanning is that it adds compliance costs for businesses looking to get into the mobile operating system space. While Google and Apple dominate the space right now, there are lots of smaller companies creating mobile operating systems too, including community projects with very shallow pockets. How are these smaller competitors supposed to implement sophisticated nudity detectors? Simply put, they can’t. Then the government goes after them, causes them to shut down, and Google and Apple have less competition. Image via Aurora Store For us users who value sovereignty over our technology, this development will force us to seek freedom-respecting alternatives. The simplest path forward will likely be to install a custom ROM on an Android device; however, kicking Google off the phone with its black box nudity blocker could also make it harder to access apps such as banking apps, which tend to need you to pass Google's integrity checks. Thankfully, Google Play Store apps can still be obtained by storefronts such as the Aurora Store, but it just adds to the friction. To be fair to those pushing this measure to protect children, I think it will be reasonably effective, but people will still try to find ways around it, just as they’ve done with age gates on adult websites introduced under the Online Safety Act. In the effort to find circumvention methods, it could lead users to join riskier platforms that introduce new dangers. This effort also diverts resources from proven interventions such as law enforcement cooperation, targeted investigations, education, and support services to broad technical controls that have uncertain effectiveness (due to their newness). If the government is set on introducing such tools, then there ought to be safeguards in place. Any mandated code should be released as free software so that it can be audited, and the binaries should be reproducible builds so that the public knows nothing has been tampered with in the code used to create the binaries shipped out. Ideally, these tools should also be voluntary, opt-in, and even community-run. This would also allow people to have full control over their hardware while allowing parents to flip a switch to turn on these protections for children, with the knowledge that the code being run is doing exactly what it says on the tin, and nothing nefarious, like a black box solution could be doing. The government should also have a narrow legal scope where this technology stays with blocking nudes and not spreading to blocking political opinions, hate speech, and so on. Ideally, any implementation should avoid identity-linked age verification to keep user data safe, and matching should be done locally with no server telemetry to ensure it is truly on-device. While I do understand that stakeholders such as parents want to keep children safe, the potential for abuse with this type of software is colossal. It would entrench black-box surveillance and take away our freedom to use our devices as we want. There is also the acute risk that the government will demand this surveillance be expanded to block other activities, which could be particularly dangerous. If you are in the UK and don’t wish to see these measures implemented, it is still possible to write to your MP, which could lead to some better safeguards being introduced before it’s too late. Once we get more technical information about how this will be implemented, then we will be able to see if de-Googling Android devices will bypass this measure. For anyone with an iPhone, there is zero chance that you’ll be able to take off these handcuffs because Apple doesn’t let you mess with your software.
  • Recent Achievements

    • Very Popular
      Captain_Eric earned a badge
      Very Popular
    • One Month Later
      amusc earned a badge
      One Month Later
    • One Month Later
      DJC50PLUS earned a badge
      One Month Later
    • Week One Done
      DJC50PLUS earned a badge
      Week One Done
    • Proficient
      Eric Biran went up a rank
      Proficient
  • Popular Contributors

    1. 1
      +primortal
      511
    2. 2
      PsYcHoKiLLa
      220
    3. 3
      ATLien_0
      92
    4. 4
      +Edouard
      90
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!