Form Hidden Field Substitution - javascript

I'm building a form using Expression Engine's Safecracker module.
One of the the required fields is the Title, which becomes the title of the EE channel entry.
What I'd like to do is set the Title field to be the combined first name and last name fields.
I started with this:
<form method="POST" action="#">
<input id="student_first_name" type="text" size="30" name="student_first_name">
<br>
<input id="student_last_name" type="text" size="30" name="student_last_name">
<br><br>
<input type="text" name="title" value=""/>
</form>
And then added this:
$(function() {
$('#student_first_name').keyup(function() {
var snamef = $(this);
});
$('#student_last_name').keyup(function() {
var snamel = $(this);
});
$("input[name='title']").val(snamel + " " + snamef);
return false;
});​
​I can't get it to work, though: http://jsfiddle.net/tylonius/CY5zJ/4/
Am I missing a step (or just totally doing it wrong?)?
Also, am I possibly working too hard and Safecracker already has this function built in; similar to its live UrlTitle(); function?
Any help is appreciated.
Thanks,
ty

If I understood right your question try this:
First set an id on your desired input element, like this :
<input type="text" name="title" id="student_title" value=""/>
And then :
$(function() {
changeFunction = function() {
$('#student_title').val($('#student_first_name').val() + ' ' + $("#student_last_name").val());
}
$('#student_first_name').keyup(changeFunction)
$('#student_last_name').keyup(changeFunction);
});

Better yet, avoid using javascript altogether and just use SafeCracker's dynamic_title parameter.
dynamic_title="[student_first_name] [student_last_name]"

user1236048 has the best solution for you but below is a working version of your code
$(function() {
var snamef;
var snamel;
$('#student_first_name').keyup(function() {
snamef = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
$('#student_last_name').keyup(function() {
snamel = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
return false;
});
and here is the working jsfiddle

Related

Enable button only if text is filled in (NO SPACES)

I've looked around for an answer to my question, but all the solutions I have found do not take into account that spaces also work as input.
I have a join function, and the button shouldn't be enabled if a user only enters space. It should need actual text. Anyone has a solution to this?
Here's my function:
$("#join").click(function(){
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
$("#login").detach();
$("#UsersOnline").show();
$("#msg").show();
$("#messaging").show();
$("#msg").focus();
ready = true;
}
you could use jquery trim()
var name = $.trim($("#name").val());
https://api.jquery.com/jQuery.trim/
EDIT:
As #David Thomas pointed out, we can also use String.prototype.trim()
var name = $("#name").val().trim();
function updateResult() {
var before = $("#name").val().replace(/\s/g,'SPACE');
var name = $("#name").val().trim();
$('#result').text('Before:' + before + "\nAfter:" + name);
}
$(document).ready(function(){
updateResult();
$('body').on('keyup','#name',function(){
updateResult();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>By default value i left left a space for the name</p>
Name : <input type="text" id="name" value=" "><br>
<br>
Value of name : <pre id="result">empty</pre>

Jquery one button updates multiple input fields on form

I am trying to update two input fields in a form when clicking one button. I actually had all the code right when using document.getElementById, but the form that I'm using strips the ID's I set away, so I can't use getbyid. If I know the form field name, how could I change my function to do the same thing? Please note that my form has more than two fields, including a submit button, so I don't want to update those.
This is what I used before (with the ID selector)
Html:
<input type="text" name="field-1" id="info1">
<input type="text" name="field" id="info2">
Populate
JS:
function addTxt(val, id,no)
{
var id = id;
for(var i=1;i<=no;i++){
document.getElementById(id+i).value = val[i-1];
}
}
Fiddle:
http://jsfiddle.net/qwz47phx/3/
Edited with a much simpler and readable approach
function addVal(obj) {
event.preventDefault(); // Prevent page scrolltop on anchor click
$.each(obj, function(k, v) {
$("input[name='"+ k +"']").val( v );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo">
<input type="text" name="bar">
<a href="#" onclick='addVal({foo:"Hello", "bar-baz":"World"})'>Populate</a>
Or with native JS (ES5+):
function addVal(obj) {
Object.keys(obj).forEach(function(name) {
document.querySelector('input[name="' + name + '"]').value = obj[name];
});
}
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="name-with-dashes">
<a href="#" onclick='addVal({foo:"Hello", bar:"World", "name-with-dashes": "Works !"})'>Populate</a>
If you have problems with IDs you can use querySelector to select inputs by name like this:
JS:
function addTxt(val, id, no) {
for (var i = 1; i <= no; i++) {
document.querySelector('input[name="' + id + i + '"]').value = val[i - 1];
}
}
HTML:
<input type="text" name="info1" id="info1">
<input type="text" name="info2" id="info2">
Populate
Demo: http://jsfiddle.net/iRbouh/qwz47phx/6/
I hope this will help you.
You can use a jQuery attribute= selector to grab by name instead of ID.
function addTxt(val, id,no)
{
for(var i=1;i<=no;i++){
var name = id+i;
$("input[name='"+name+"']").val(val[i-1]);
}
}
Please note that this function will be looking for names of info1, info2, info3, etc, just as your original script did. However, in the HTML, you have names of info and info-1. Either the names will have to be changed to fit the function, or the function can be slightly more intricate.
Fiddle: http://jsfiddle.net/qwz47phx/8/

dynamically add, validate and remove sets of form fields

I'd like to create a webpage where the user can add and remove sets of form fields by means of one add button and remove buttons related to the set to be removed. Entered values will be checked by means jquery validate, for which rules are added dynamically as well. pls see an an simplified example below of my targeted form:
What is a good structure of javascript code for adding, removing and validate sets of forms fields? I googled -also on this site- and there are many javascript examples for adding sets of formfields. I like the example I found at view-source:http://www.coldfusionjedi.com/demos/jqueryvalidation/testadd.cfm, which uses a form template. But I struggle in particular with the javascript coding for the removing buttons..(which are not in the example)
my targeted (simplified) form (template with 1 set of 3 formfields):
<form name="myForm" id="myForm" method="post" action="">
<input id="name1" name="name1" />
<input id="email1" name="email1" />
<input id="phone1" name="phone1" />
<input type="submit" value="Save">
</form>
I think that you should template the form. I.e. wrap it in a function, so you can create it again and again. Here is a jsfiddle http://jsfiddle.net/krasimir/2sZsx/4/
HTML
<div id="wrapper"></div>
add form
JS
var wrapper = $("#wrapper");
var addForm = $("#add-form");
var index = 0;
var getForm = function(index, action) {
return $('\
<form name="myForm" id="myForm" method="post" action="' + action + '">\
<input id="name' + index + '" name="name' + index + '" />\
<input id="email' + index + '" name="email' + index + '" />\
<input id="phone' + index + '" name="phone' + index + '" />\
<input type="submit" value="Save">\
remove form\
</form>\
');
}
addForm.on("click", function() {
var form = getForm(++index);
form.find(".remove").on("click", function() {
$(this).parent().remove();
});
wrapper.append(form);
});
Simple validation can be done when your form is submitted, thus:
$('#myForm').submit({
var n1 = $('#name1').val();
var e1 = $('#email1').val();
var p1 = $('#phone1').val();
if (n1=='' || e1=='' || p1=='') {
alert('Please complete all fields');
return false;
}
});
Note that the return false will abort the submit and return user to the document.
Great code for adding/removing form fields can be found in this question: https://stackoverflow.com/questions/18520384/removing-dynamically-generated-textboxes-in-jquery
jsFiddle here
If you are using KeenThemes (maybe Metronic theme)
https://preview.keenthemes.com/good/documentation/forms/formvalidation/advanced.html
You can do like this.
var form = document.getElementById('form_id');
var validator = FormValidation.formValidation(
form,
{
fields: {
name: {
validators: {
notEmpty: {
message: 'Please enter template name'
},
stringLength: {
min: 3,
trim: true,
message: 'Please enter a longer name.'
},
}
},
...
more fields here
...
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap: new FormValidation.plugins.Bootstrap(),
},
});
function addNewFieldDynamically() {
// add new field here
...
validator.addField('field_name', {
validators : {...}
})
}
function removeFieldDynamically() {
// remove a field here
...
validator.removeField('field_name')
}

Build, Modify, Output Javascript Array

I'm trying to accomplish the following...if it's asking too much in a single question then some simple steps on what events to use will still help.
There are 2 blank textareas sitting next to eachother - Input and Output. Between them are two inputs Before and After. I want to type or paste a list of words into Input separated by line break, for example:
melons
peaches
apples
And then use the Before and After inputs to add in a word/phrase/symbol before and after each keyword. So if I type 'buy' in before and 'today' in after, the Output text area will display:
buy melons today
buy peaches today
buy apples today
I'd like to accomplish this without having any page refreshing. We can assume the form elements are named as follows:
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
I've been try to at least get the Input text to display in Output using this code, but that's not even working:
$(document).ready(function(){
$('#input').keyup(function(e){
$('#output').html($(this).val());
});
});
Any guidance would be awesome!
a compact one:
$("#input,#before,#after").on("keyup", function () {
$("#output").val(
$.map($("#input").val().split("\n"), function (n, i) {
return $("#before").val() + " "+ n + " " + $("#after").val();
}).join("\n"));
});
example
This would do the trick:
function update_output(){
//Split input by newline
var input_words = $('#input').val().split('\n');
var output_lines = new Array();
//Iterate over each keyword and prepend and append values
$.each(input_words, function(i, word){
output_lines.push($('#before').val()+' '+word+' '+$('#after').val());
});
//Display output in textarea
$('#output').val(output_lines.join('\n'));
}
You just need to choose when you want to update the output textarea, maybe bind it so it updates every time the #input or #before and #after changes:
$('#input,#before,#after').on('change',update_output);
Alright, I can help you to get started. My answer is not complete, but you can have a very good idea from here. Note I wrote this code to be easy to understand and I am not using sophisticated approaches on purpose.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#input").keypress(function(key){
if(key.which == 13) {
refreshData();
}
});
});
function refreshData() {
var beforeVal = $("#before").val();
var inputLines = $("#input").val().split(/\r\n|\r|\n/g);
var desiredOutputVal = "";
for(var i=0; i<inputLines.length; i++) {
desiredOutputVal += beforeVal + inputLines[i] + "\n";
}
$("#output").val(desiredOutputVal);
}
</script>
</head>
<body>
<form>
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
</form>
</body></html>

mootools toQueryString of a Form

im trieing to serialize a complete form. i found the easiest way:
var tmp = $('myForm').toQueryString().parseQueryString();
var req = JSON.decode( tmp );
but it wont work.
i testet only
var tmp = $('myForm').toQueryString()
alert("data " + tmp);
also wont work. it only prints "data " nothing more..
my form is simple:
<form action="test.php" id="myForm">
<input type="text" name="user">
<input type="text" name="user_name">
<input type="submit" name="user_name_button">
</form>
the javascript code is like:
$('myForm').addEvent( 'submit', function( e )
{
e.stop();
var tmp = $('myForm').toQueryString()
alert("data " + tmp);
})
does anybody has an idea why this didn work ?
Found the error. The submit and one text field had the same name.
See the fixed version here, http://jsfiddle.net/HXsBk/1/

Categories

Resources