Dynamic Form Input Based on Anchor Value - javascript

I have the following snippets that open a single Modal Form:
<a class="modalbox" id="foo" href="#inline">Request a Quote</a>
<a class="modalbox" id="bar" href="#inline">Request a Quote</a>
...and so on...
Somehow, I need to render the value of ID in the input "sub" in the following HTML form
as well as concatenate the ID with some predetermined text, which is "I am interested in..."
<form id="contact" name="contact" action="#" method="post">
<input type="hidden" id="product" name="product" value="">
<label for="sub">Subject:</label>
<input type="sub" id="sub" name="sub" class="txt" value="I am interested in '$id'">
<button id="send">Submit</button>
I'm already using Javascript for verification and AJAX for processing to PHP script.
Edit:
This is the Javascript already being used to populate the hidden input above, which is working perfectly:
$('a').click(function(e) {
$('#product').val($(this).attr('id'));

I'd suggest, with plain JavaScript, something like:
function addTextToInput(from, to, prefix, e) {
e = e || window.event;
if (!from || !to) {
return false;
}
else {
from = from.nodeType == 1 ? from : document.getElementById(from);
to = to.nodeType == 1 ? to : document.getElementById(to);
var text = from.id;
to.value = prefix ? prefix + ' ' + text : text;
}
}
var as = document.querySelectorAll('a.modalbox');
for (var i = 0, len = as.length; i<len; i++) {
as[i].onclick = function(e) {
addTextToInput(this, 'sub', 'I am interested in', e);
};
}​
JS Fiddle demo.
But given that you already seem to be using jQuery:
$('a.modalbox').click(function(e){
e.preventDefault();
$('#sub').val('I am interested in ' + this.id);
});
JS Fiddle demo.

Related

How to use data-display with multiple inputs?

I have a form wizard, in the last step I want display a preview of the form data submitted. I'm using data-display attribute to do that. I have multiple inputs with same name:
<input type="text" class="form-control input_nb" name="num_espece[]" placeholder="Indiquer le nombre">
and this is how I display in the final step:
<p class="form-control-static display-value" data-display="num_espece[]"></p>
and this is the script used for that:
f = function() {
$(".display-value", form).each(function() {
var a = $('[name="' + $(this).attr("data-display") + '"]', form);
"text" == a.attr("type") || "email" == a.attr("type") || a.is("textarea") ? $(this).html(a.val()) : a.is("select") ? $(this).html(a.find("option:selected").text()) : a.is(":radio") || a.is(":checkbox") ? $(this).html(a.filter(":checked").closest("label").text()) : "card_expiry" == $(this).attr("data-display") && $(this).html($('[name="card_expiry_mm"]', form).val() + "/" + $('[name="card_expiry_yyyy"]', form).val())
})
},
When I'm in the preview step I get only the value of the first input displayed. What should I do to get the values of all inputs displayed ?
Welcome Youssef, if I understood you well, you want everything inside your form to be shown after submit
Let's suppose this is your form
<form>
<input placeholder="Your name" required>
<input type="email" placeholder="Your email" required>
<textarea placeholder="Your comment"></textarea>
<button>Check</button>
</form>
You just need to get all items and show their values.
// Avoid submit button
const $items = document.querySelectorAll('form > *:not(button)')
// On submit
document.querySelector('form').onsubmit = e => {
// Show all data
document.body.innerHTML = [...$items].reduce((acc, e) =>
acc += `${e.placeholder} = ${e.value}<br>`, '')
// Aborting real submit, this is just an example
e.preventDefault()
}
Instead of document.body you can use document.querySelector('p.display-value')
https://jsfiddle.net/3mc29vyj/
Hope this help or at least point you to the right direction : )
If I understood you correctly you want to add all input values into one <p> tag, right?
Right now you iterate over all <p class="display-value"> tags and then find all elements with the same name provided in the data-display attribute. Your var a now contains a list of elements but in your code you treat it as a single element. You need to loop over all fields and append the values to the display element, $(this).html(...) will overwrite it so you want to append the text via $(this).append(...).
Code sample
f = function() {
var form = $("form");
$(".display-value").each(function() {
$(this).html('');
var as = $('[name="' + $(this).data("display") + '"]');
if (as && as.length) {
for (var i = 0; i < as.length; i++) {
var a = $(as[i]);
"text" == a.attr("type") ||
"email" == a.attr("type") ||
a.is("textarea")
? $(this).append(a.val())
: a.is("select")
? $(this).append(a.find("option:selected").text())
: a.is(":radio") || a.is(":checkbox")
? $(this).append(
a
.filter(":checked")
.closest("label")
.text()
)
: "card_expiry" == $(this).attr("data-display") &&
$(this).append(
$('[name="card_expiry_mm"]', form).val() +
"/" +
$('[name="card_expiry_yyyy"]', form).val()
);
}
}
});
};
A demo can be found in this Codepen.

How do I keep single checkbox stay checked after refreshing the page?

HTML code:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
This will make the checkbox stays checked, but when page is refresh or exit and comes back, the checkbox will be unchecked. Therefore, after some research, I tried the localStorage, but doesn't seem to quite figure it out yet.
localStorage code:
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {};
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
I have script tags around the localStorage code and after implementing these codes, my checkbox still doesn't stays checked.
Both code as a whole:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" name="new_background"/>
</div>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
</script>
<input type="submit" name="submit" value="Upgrade Background" class="button"/>
</form>
</div>
I would like to thank everyone that took time to help me figure out the solution to my question with the biggest thanks to #Pranav C Balan!!! Check out the finished code # http://stackoverflow.com/a/44321072/3037257
I think your code is executing before the form elements are loading, so place it at the end of your code or wrap it using document ready handler to execute only after the elements are loaded. If you were placed the code before the element $("#checkbox-container :checkbox") would select nothing since it is not yet loaded in the DOM.
One more thing to do, in your code the checkbox doesn't have any id so add a unique id to the element to make it work since the JSON is generating using the id value.
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
</div>
Working demo : FIDDLE
<script>
// document ready handler
// or $(document).ready(Function(){...
jQuery(function($) {
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
});
</script>
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
Working demo : FIDDLE
An alternative to localStorage that only utilizes document.cookie:
$('input:checkbox').change(function() {
saveCookies();
});
To register the function and the actual function:
function saveCookies() {
var checkArray = [];
$('input.comic-check').each(function() {
if ($(this).is(':checked')) {
checkArray.push(1);
} else {
checkArray.push(0);
}
});
document.cookie = "checks=" + checkArray;
}
This is an alternative to localStorage, and depends on whether you want it to persist longer
And to retrieve the saved (on load)
var checks = getCookie("checks");
if (checks != "") {
checkArray = checks.split(',');
//unchecks boxes based on cookies
//also has backwards compatability provided we only append to the list in landing.ejs/generator.js
for (var i = 0; i < checkArray.length; i++) {
if (checkArray[i] == "0" && $('input.comic-check').length > i) {
var checkBox = $('input.comic-check')[i];
$(checkBox).prop('checked', false);
}
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Three situations you will need to check the checkbox
PHP have it set to checked="checked" (checked)
localStorage have it as true (checked)
all other situations this should be unchecked
all you need is to make sure first two situation you check the checkbox, then by default it is unchecked, but in your each you are also uncheck checkbox, therefore ignored the PHP part (as php set it to checked but localStorege set it to unchecked)
Example here: https://jsfiddle.net/dalinhuang/efwc7ejb/
//on page load
$.each(checkboxValue, function(key, value) {
if(value){
$("#" + key).prop('checked', value);
}
});
I would change:
<?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>
for:
<?php echo (isset($_POST['new_background']) && $_POST['new_background']=="on")? "checked" : "";?>
In inline HTML, you don't need the checked attribute to be checked=checked.
Just checked is enought.
checked=checked is used in JavaScript to programatically check a checkbox.
EDIT
About your localStorage...
I made an example for you on CodePen
//on page load, check the appropriate checkboxes.
var onloadChecks = JSON.parse(localStorage.getItem("checkboxValue"))
$.each(onloadChecks, function(key, value){
$("#" + key).prop('checked', value);
});
// ================ Saving checks
// Checkboxes collection.
var allCheckboxes = $("input[type='checkbox']");
// On change handler.
allCheckboxes.on("change", function() {
// Check how many checkboxes we have.
var jsonCheckboxes = {};
console.log("There is "+allCheckboxes.length+" checkboxes.");
// Building the json.
for(i=0;i<allCheckboxes.length;i++){
console.log(allCheckboxes.eq(i).attr("id"));
console.log(allCheckboxes.eq(i).is(":checked"));
jsonCheckboxes[allCheckboxes.eq(i).attr("id")] = allCheckboxes.eq(i).is(":checked");
}
console.log("jsonCheckboxes: "+JSON.stringify(jsonCheckboxes));
// Setting localStorage.
localStorage.setItem("checkboxValue", JSON.stringify(jsonCheckboxes));
console.log("LocalStorage: "+ localStorage.getItem("checkboxValue") );
});
Working around your comment : my goal is to find something that will make my checkbox stays checked if the user choose to, here's a way to have the localStorage handle it :
jQuery (3.2.1)
$(document).ready(function() {
var bground = localStorage.getItem('background'); // get the value if exists
if (bground == 'shadow') { // checkbox has been previously checked
$('#checker').attr('checked', 'checked');
}
if (bground == 'shadowless') { // checkbox has been previously unchecked
$('#checker').attr('');
}
$('#submit').submit(function() { // when form is submitted
bground = localStorage.getItem('background'); // get the value in LS
if($('#checker').is(':checked')) // is it checked or not ?
{ sh = 'shadow'; } else { sh = 'shadowless'; }
localStorage.setItem('background', sh); // update LS with new value
});
});
HTML (added id="submit" to form)
<form action="" id="submit" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
This will make the checkbox stays checked, and when page is refreshed, the checkbox will be checked/unchecked depending on user's previous choice.
You could also use the jQuery change function instead of form submitting.
Just modify the line :
$('#submit').submit(function() { // comment/delete this line
// to the one below
// $('#checker').change(function() { // uncomment this line

Specify first character of input

I have an input where I want the first character to be #.
That means if the user writes something, it automatically adds the #, or better, the # is already present in the input.
How do I do that? I thought i could do that with jQuery mask but I couldn't make it work.
Here is the code,
$("#your-input-id").keypress(function(e) {
if (e.keyCode != 8) {
var text = this.value;
if (text.length == 0) {
this.value = text + '#';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="#">
<input id="your-input-id" type="text" placeholder="Type a text here..." data-prefix="#" />
</form>
Hope this will work.
This will append # when you will start typing, and it will append everything later to #.
EDIT
$("#your-input-value").keydown(function(e) {
var cur_val=$(this).val();
var field=this;
setTimeout(function () {
if(field.value.indexOf('#') !== 0) {
$(field).val(cur_val);
}
}, 1);
});
See this solution http://codepen.io/bachors/pen/yeJOrg
Running example to meet your needs:
/***********************************************
* #### jQuery Prefix Input ####
* Coded by Ican Bachors 2015.
* http://ibacor.com/labs/jquery-prefix-input/
* Updates will be posted to this site.
***********************************************/
$(".yourClass").focus(function(){var a=$(this).data("prefix"),ibacor_currentId=$(this).attr('id'),ibacor_val=$(this).val();if(ibacor_val==''){$(this).val(a)}ibacor_fi(a.replace('ibacorat',''),ibacor_currentId);return false});function ibacor_fi(d,e){$('#'+e).keydown(function(c){setTimeout(function(){var a=bcr_riplis($('#'+e).val()),qq=bcr_riplis(d),ibacor_jumlah=qq.length,ibacor_cek=a.substring(0,ibacor_jumlah);if(a.match(new RegExp(qq))&&ibacor_cek==qq){$('#'+e).val(bcr_unriplis(a))}else{if(c.key=='Control'||c.key=='Backspace'||c.key=='Del'){$('#'+e).val(bcr_unriplis(qq))}else{var b=bcr_unriplis(qq)+c.key;$('#'+e).val(b.replace("undefined",""))}}},50)})}function bcr_riplis(a){var f=['+','$','^','*','?'];var r=['ibacorat','ibacordolar','ibacorhalis','ibacorkali','ibacortanya'];$.each(f,function(i,v){a=a.replace(f[i],r[i])});return a}function bcr_unriplis(a){var f=['+','$','^','*','?'];var r=['ibacorat','ibacordolar','ibacorhalis','ibacorkali','ibacortanya'];$.each(f,function(i,v){a=a.replace(r[i],f[i])});return a}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="#">
<input id="yourInput" class="yourClass" type="text" placeholder="Type a text here..." data-prefix="#" />
</form>
You can try this,
HTML
<input type="text" class="txtUrl" />
Javascript
$('.txtContent').keydown(function(e) {
var cur_val = $(this).val();
if(cur_val.length == 0) {
$(this).val('#' + cur_val);
}
});
Here is the working fiddle: http://jsfiddle.net/jMH9b/43/
Hope this helps!
As you stated, if there is already a SLASH it should not do anything. Here is the solution
$('#description').bind('input', function(event){
var currentVal = $(this).val();
$(this).val(currentVal.indexOf('#') !== 0 ? ('#' + currentVal) : currentVal)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label name="description">Enter some text</label>
<input type="text" id="description" name="description">
<input id='e' onKeyup='test(this)' value='#'/>
var input = document.getElementById('e');
function test(e){
input.value = e.value.charAt(0) !== '#' ? input.value = '#' + e.value : e.value
}
hope this helps...

How to make a word a link if the user has input # before it?

I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.

Without using a form, how can I check an input field is not empty before running function?

I have the following code in a SharePoint aspx page ( I got an error that said I cannot use form controls... that is why the form tags are not there):
<div id="formBox">
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' />
<input name="codename" type="radio" value="codeA" /> <label for="x">X</label> <input name="codename" type="radio" value="codeB" /><label for="y">Y</label>
<input type='button' onclick='javascript:changeText2()' value='Change Text'/>
</div>
Here is the function which is supposed to concatenate the information: It works... kind of.. parts of it.
It will add the selected button to the url, and also the input text. However, it is firing before the input is filled out, and then works once you type in the box again.
I tired to add in if statement, to stop the code if the box was not filled out but it didn't work. Here is what I have...
function changeText2(){
var userInput = document.getElementById('userInput').value;
$('#formBox input[type="text"]').on('change', function() {
var linktest = 'site/info.aspx?' + $('input[name="codename"]:checked', '#formBox').val() + '=' + userInput;
alert(linktest);
});
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
I tried to check the input box like this, but it didn't work:
if( $('#formBox input[type="text"]').val== "") {
alert('no info');
}
It should be val() in jquery, not val. However, it will be value in javascript, not val. Simply just use unique id, try something like this,
For Jquery:
if( $('#userInput').val() === "") {
alert('no info');
}
For javascript:
if(document.getElementById("userInput").value === "") {
alert('no info');
}

Categories

Resources