Form field (default text) + some more text - javascript

I have a form field with default text, but my users have to paste a filename after this default text. How can I achieve that?
/td><th width="200px">VideoLink</th><td><input type="text" id="VideoLink" name="VideoLink" value="<?php echo $video_rec['VideoLink']; ?>"></input></td>
$video_rec['VideoLink'] = "rtmp://test123.cloudfront.net/cfx/st/mp4:";
My user has to paste the filename in that form field, but when the form is submitted that field should contain rtmp-url + filename (test.mp4)
Sample = rtmp://test123.cloudfront.net/cfx/st/mp4:TEST.mp4
I did check this solution How to keep some default text in the input field?, but when i right click to paste it removes the default text.

Something like this:
HTML:
<input type="text" id="defaultLink" name="defaultLink" class="defaultLink"
value="rtmp://test123.cloudfront.net/cfx/st/mp4:" disabled />
<input type="text" id="videoLink" name="videoLink" />
<input type="hidden" id="completeLink" name="completeLink" />
<input type="button" onclick="appendLink();" value="Append" />
CSS:
.defaultLink {
min-width: 235px;
border: none;
background-color: transparent;
}
JS:
function appendLink(){
var defaultLink = document.getElementById('defaultLink').value;
var videoLink = document.getElementById('videoLink').value;
var completeLink = defaultLink + videoLink;
alert(completeLink);
document.getElementById('completeLink').value = completeLink;
}
Then, you can get complete URL from completeLink request attribute / parameter.
DEMO

You shouldn't trust your users to provide correct input, let them paste as they wish, you can guide them with a note or label, ex. please include the "rtmp://" bit but ultimately you should validate the input server side.
You can try this:
$string = 'rtmp://test123.cloudfront.net/cfx/st/mp4:TEST.mp4';
//$string = 'test123.cloudfront.net/cfx/st/mp4:TEST.mp4';
// make sure to also strip any leading or trailing whitespace using trim()
// you can also process the input string even further before testing the protocol
if (!stripos($string)){
$url = 'rtmp://' . trim($string);
}
else{
$url = trim($string);
}
print $url;

Related

Possible to leave out ID[] from url?

I have alot of data, that i can check, useing checkbox. when I 'Submit', and want to see all the data i checked, i get redirected to the result page. But lets say i choose to only check 1 element the URL is: http://XXX.xxx/Test/TestResults?ID%5B%5D=2728
this is okay, but lets say i choose to see 10 elements the URL is LONG:
http://XXX.xxx/Test/TestResults?ID%5B%5D=2728&ID%5B%5D=2726&ID%5B%5D=2727&ID%5B%5D=2725&ID%5B%5D=2724&ID%5B%5D=2723&ID%5B%5D=2722&ID%5B%5D=2721&ID%5B%5D=2720&ID%5B%5D=2719
and the problem is that if i choose to see 100 elements, the URL will become so long that the site can alert me with: 'Submitted URI too large!'
is there any way only to show the id number, and not the ID[] (ID%5B%5D)?
The ID[] is the ID%5B%5D part, and then the id number will be added to it.
echo "<input type = 'checkbox' name = 'ID[]' class = 'checkbox' value = '".$testjobids[$count]."'/>";
/*this is in another .php file where i get the ID*/
$SelectedTestjobids = $_GET['ID'];
Link is shorter
After useing _POST, i got this: http://XXX.xxx/Test/TestResults
Problem
The only problem i have now is that i can't link this site to anyone, because there isn't attached anything else but the site in the URL. Is there a way to make a uniqe number after the http://XXX.xxx/Test/TestResults, so it's possible to share the link and it stills shows the same data?
If you can't use a post request for some reason, you could copy the values you want and submit them as a more compact string, either manually or by adding the string to another form element before submitting.
Of course, your server code would have to know what to do with the comma-separated string when it receives it.
This example uses a hidden <textarea> element to hold the values:
// Identifies HTML elements
const
boxes = document.querySelectorAll(".box"),
area1 = document.getElementById("area1"),
btn1 = document.getElementById("btn1"),
div1 = document.getElementById("div1");
// Calls `submitCheckboxValuesAsText` when the button is clicked
btn1.addEventListener("click", submitCheckboxValuesAsText);
// Defines `submitCheckboxValuesAsText`
function submitCheckboxValuesAsText(){
// Puts checked values in the textarea
updateTextarea();
// Copies the text from the textarea
const text = area1.value;
// Clears the demo div
div1.innerHTML = "";
// Formats the copied text within the demo div
if(text){
div1.innerHTML = "Imagine this gets sent to your server:<br /><br />" +
"<span class='grey'>" + text + "</span>";
}
}
// Defines `updateTextarea`
function updateTextarea(){
area1.value = [...boxes] // `[...boxes]` converts `boxes` to a proper Array
.filter(box => box.checked) // Makes a new Array of just the checked boxes
.map(box => box.value) // Makes a new Array with the values of those boxes
.join(","); // Makes a string from the array, separated by commas
}
label{ margin-right: 15px; }
#btn1{ margin: 20px 5px; }
.grey{ background-color: #DDDDDD; padding: 2px 5px; }
<label><input type="checkbox" class="box" value="val1" /><span>box1</span></label>
<label><input type="checkbox" class="box" value="val2" /><span>box2</span></label>
<label><input type="checkbox" class="box" value="val3" /><span>box3</span></label>
<textarea id="area1" hidden></textarea>
<div><button id="btn1">Submit</button></div>
<div id="div1"></div>
(If you wanted to avoid submitting manually, you should probably populate the hidden field before the user clicks Submit, such as by using document.addEventListener("change", updateTextarea);.
You would also want to change the button to <input type="submit" />.)

Change the Increment Value of HTML Number Input without changing valid values

I have an input form which looks like this:
<input type="number" value="0.00" step="0.05">
I found the step function which technically solves my increment problem changing it to 0.05 instead of the default 1. I have however not found a solution where I can change the increment without changing the valid inputs.
The input can take any number but the most common values will be in increments of 0.05. Is there a work-around for this? A solution using JavaScript is also more than welcome.
Thank you very much!
EDIT:
Adding nonvalidateto the html form-tag solved this for me. Now pressing the buttons use the increments I want but when I need to specify more accurately than the steps the form still accepts the values.
<form action="/run" novalidate>
<input type="number" value="0.00" step="0.05">
<input type="submit">
</form>
Using novalidate in the form tag will get rid of the validation for the whole form but keep the increments implemented by step.
Update
"I did add nonvalidate to the form tag. It let's me do what I want as of now but it might not be the best solution."
If you don't want your form "compromised" by novalidate, then have 2 forms:
Form A [No action or method]
All user interaction and calculations are here.
All inputs can be modified without worrying about built-in validation from the form.
Form B [Set action and method optional target]
The submit button resides within
Add a hidden input for each value on Form A you want to submit and ensure each has a name attribute and value.
Any client-side validation should be done here.
With that setup you'll need an event like onbeforesubmit so the values of Form A can transfer over to Form B before it submits to the server. Unfortunately I don't think it exist as a standard, but to emulate it is simple:
formA.onsubmit = b4Submit;
function b4Submit(event) {
hidden_Input_In_FormA.value = number_Input_With_Crazy_Step_In_FormA.value
return true;
}
So this contrived example shows an event handler that gets the value from one form then stores it in the other form. Next it continues by submitting whatever data it has. This is due to the callback returning true, should false be returned, the callback function itself dies and so does the submit event along with it.
The Demo has been updated to do what was just described above. Note: there are no novalidate attributes in use. The second form (Form B or form#tx) is sending text from a hidden input as far as it's concerned. A number like -103.002684109 is not valid if it's from an <input type='number'> but from a text or hidden input, it is just text (although I believe the actual data in most form controls is actually a string not a number).
"The input can take any number but the most common values will be in increments of 0.05. Is there a work-around for this? A solution using JavaScript is also more than welcome."
You can change any attribute you want on any tag AFAIK. Programatically the syntax is simple with Plain JavaScript:
Object.property = "string"
Object: a referenced <element> tag
property: when you reference an standard attribute like a property it's becomes a property.
string: the value must be a string
Here's a basic way of changing a standard attribute programmatically:
var obj = document.querySelector('a');
obj.href = "https://google.com"; //
The following Demo uses:
Document.Forms
HTMLFormElement.elements
HTMLFormControlsCollection
Dot Notation
Demo
Demo can send to a live test server the response is sent to an iframe to view
var ui = document.forms.ui;
var tx = document.forms.tx;
var u = ui.elements;
var x = tx.elements;
var D = u.digit;
var C = x.cache;
var lo = u.min;
var hi = u.max;
var inc = u.step; // I think this what you specificly
var t = u.type;
var chg = u.change;
chg.onclick = chgAttr;
tx.onsubmit = cacheVal;
function chgAttr(e) {
D.min = lo.value;
D.max = hi.value;
D.step = inc.value;
D.type = t.value;
}
function cacheVal(e) {
C.value = D.value;
return true;
}
body {
font: 400 16px/1.5 'Consolas'
}
#digit {
margin-right: 15px;
}
input,
output,
button,
select,
option,
label {
display: inline-block;
font: inherit
}
select {
padding: 3px 5px
}
[type='submit'] {
float: right;
}
<!doctype html>
<html>
<head>
<title></title>
<meta charset='utf-8'>
<style></style>
</head>
<body>
<form id='ui' oninput='out.value = digit.value'>
<fieldset>
<legend>Click Button to Change Input</legend>
<input id='digit' min='' max='' step='' type='number'>
<button id='change' type='button'>CHANGE</button>
<output id='out' for='digit'></output>
</fieldset>
<fieldset>
<legend>Attribute Adjustments</legend>
<input id='min' min='-2147483648' max='2147483648' type='number' placeholder='min'>
<input id='max' min='-2147483648' max='2147483648' type='number' placeholder='max'>
<input id='step' type='number' placeholder='step'>
<label for='type'>Type:
<select id='type'>
<option>number</option>
<option>text</option>
<option>range</option>
<option>hidden</option>
<option>color</option>
<option>time</option>
</select>
</label>
</fieldset>
</form>
<form id='tx' action='https://httpbin.org/post' method='post' target='response'>
<input id='cache' name='cache' type='hidden'>
<input type='submit'>
</form>
<iframe src='about:blank' name='response'></iframe>
<script></script>
</body>
</html>

Simple HTML form input field with multiple values from barcode scanner

I know barcode scanner is just another keyboard that sends keycode 13 after every scan, I have a very simple form with just one input field, I want to be able to scan multiple barcodes and click submit to POST data. I think I would would need a javascript for this, but I am no good with javascripts.
The end result would look something like this. You can see multiple barcodes have been scanned and they appear at the bottom of the picture.
The goal is to scan desired number of barcodes without touching the keyboard, when done scanning press the submit button with the click of mouse. When I click submit they should be posted to another page.
I am sure this is a simple thing for someone who is good at javascript.
Here is the HTML form code.
<form action="myform5.php" method="post">
<p>First name: <input type="text" name="serial" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
My question is how I can make it do what I described above?
Thanks in advance.
This should work.
var codes = "";
var codes_el = document.getElementById('codes');
var output_el = document.getElementById('output');
function process_key(event){
var letter = event.key;
if (letter === 'Enter'){
event.preventDefault();
letter = "\n";
event.target.value = "";
}
// match numbers and letters for barcode
if (letter.match(/^[a-z0-9]$/gi)){
codes += letter;
}
codes_el.value = codes;
output_el.innerHTML = codes;
}
<form method="POST" action="myform5.php">
<input onkeydown="process_key(event)" />
<input type="submit" value="Send" />
<input type="hidden" name="codes" id="codes" />
</form>
<pre id="output">
</pre>
Then you can get in myform5.php like so:
<?php
// codes will be a string of barcodes seperated by "\n"
$codes = $_POST['codes'];
// get as array like so
$barcodes = explode("\n", $codes);
// build up string of barcodes
$barcode_str = "";
$prefix = '';
foreach ($barcodes as $barcode){
$barcode_str .= $prefix . "'" . $barcode . "'";
$prefix = ', ';
}
$query = "select * from hdds where serial IN (" . $barcode_str . ");";
/* do things with query here */
// once your done processing
// redirect the user back to the form page
header("Location: FormPage.html");
?>
I assume your barcodes are strings in the DB.
So you have to wrap each of the barcodes in the query.

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

Javascript onKeyUp condition doesnt work when speed typing

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">

Categories