Help with this criteria ?
Users can be able to add as many Names as they want, ADD NAME link serves the purpose for this.
How can I handle this specification ?
Please check the spec below:
Thanks.
var input = $('#input').clone().attr('name', 'name2').attr('id', 'input-2').appendTo('body')
You can go further and clone the entire row/div with $(el).clone() and then do .find('input') and modify the name and id attribute values so they're unique and don't conflict. You can pass true to clone if you want to copy the event handlers.
Incomplete non-jQuery "solution" since I don't know exactly at which point the OP is in since he claims he can clone nodes now..
<div id="wrap">
<div class="foo">
<label for="first_name">name:</label><input type="text" name="first_name[] " id="first_name">delete
</div>
add name
</div>
<script>
(function() {
var add = document.getElementById('add'), counter = 0;
add.onclick = function() {
var rows = document.getElementsByTagName('div'), last = false;
if ( rows.length ) {
for ( var i = rows.length; i--; ) {
if ( last ) { break; }
if ( rows[i].className.length && ( ' ' + rows[i].className + ' ' ).indexOf(' foo ') != -1 ) {
last = rows[i];
}
}
}
if ( last ) {
var newNode = last.cloneNode(true), wrap = document.getElementById('wrap'), input = newNode.getElementsByTagName('input');
input.id = input.id + (counter++);
wrap.appendChild( newNode );
}
}
})();
Hope this goes well.
<html>
<script type="text/javascript">
function addfieldset() {
var namefieldset = document.getElementById("name").cloneNode(true);
document.getElementById("names").appendChild( namefieldset );
}
function deletefieldset( e ) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild( namefieldset );
}
</script>
<body>
<div id="names"><div id="name">Name: <input name="namefield" type="text"/>delete</div></div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()"/>
</body>
</html>
I remembered an excellent post from "quirkmodes" briefly explained this. I still hold in my bookmarks. Here it is.
Good Day!
Related
Can anybody help me with this problem please. I've been researching for days and I can't make the php echoed array containing html code to be formatted for the responseText of javascript.
I've tried to format the echoed array with json_encode($array) but doesn't work.
I've tried responseText.split(" ") and then used a for loop to extract the html code inside the array but I can't either.
I know the javascript code is working because I manually inserted html code like this:
i.e
responseText = '<p><img src="img/moon.png">here is your image</p>'
This works perfect.But when php spits out the array all I see on the screen with the code you see below is the Array word.
I know my php code is also working because I tested it before sending the text using POST method.
Your help is appreciated.
My ajax to php
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
</script>
<script>
function gotext(){
var mm = document.getElementById("todotext").value;
var isTr=false;
var ajaxfile = ajaxObj("POST", "env.php");
ajaxfile.onreadystatechange = function() {
if(ajaxReturn(ajaxfile) == true) {
document.getElementById("outputimgs").innerHTML = ajaxfile.responseText;
}
}
ajaxfile.send("todotext="+mm);
}
$(document).ready(function(){
$('form[name=uturn]').on('submit', function(e) {
e.preventDefault();
gotext();
$('html, body').animate({
scrollTop: $("#first").offset().top
}, 1000);
return false;
});
});
</script>
This is the html form
<form name="uturn" action="process.php" method="post">
<textarea id="todotext" name="text" placeholder="type or paste words here"></textarea><br/>
<input type="submit" id="arefbut" class="button scrolly" value="Convert"/>
</form>
<!-- First -->
<section id="first" class="main">
<div class="container">
<h2>Done !!</h2>
<p id="outputimgs">end</p>
</div>
This is the dynamic construction of html in php
if(isset($_POST['todotext'])) {
$chunk = $_POST['todotext'];
$commentArray = explode(" ",$chunk);
.
.
.
$commentArray[$i]='<p class="pos"><img src="imgs/blank.png" width="40" height="40"><br>
'.$commentArray[$i].'</p>';
$together = implode(" ",$commentArray);
echo $together;
All,
I found where the problem was. Like I said the only thing coming to the web page was the word Array; that output was coming from the str_replace, which was later changed into $commentArray[$i] in the middle of the html code to be echoed out to responseText. I had to add this for loop to fix it. I don't know off a better way to do it. The rest of the html was ignored and to fix this I added the html_entity_decode function.
The final code looks like below.
All is working perfect now.
See here the for loop added
if(isset($_POST['todotext'])) {
$chunk = $_POST['todotext'];
$text = explode(" ",$chunk);
$delimiter = array(" ",",",".","'","\"","|","\\","/",";",":","?",">","<","~","_","-","=","+","*","!","#","#","$","%","^","&","(",")");
$replace = str_replace($delimiter, $delimiter[0], $text);
for ($i=0; $i<count($replace); $i++)
{
if ($replace[$i]!==' ')
{
$newreplace .= $replace[$i].' ';
}
}
$newreplace = preg_replace('/\s+/', ' ', $newreplace );
$commentArray= explode($delimiter[0], $newreplace);
Here is the new treatment to $commentArray
for ( $i=0; $i<$counter;$i++)
{
$commentArray[$i]= html_entity_decode('<p class="pos"><img src="imgs/black.png" width="40" height="40"><br>'.$commentArray[$i].'</p>');
}
$together = implode(" ",$commentArray);
echo $together;
}
I have a form with a repeating section that uses jQuery to clone the section and increment the ids. Now I need to initialize the variables in order to send the form via PHP.
HTML:
<div class="repeatingSection">
<label for="poste_1">Poste :</label>
<input type="text" name="poste_1" id="poste_1"/>
<label for="date_1">Date :</label>
<input type="text" name="date_1" id="date_1"/>
</div>
JQUERY:
jQuery('.cloneButton').click(function(event){
event.preventDefault();
var currentCount = jQuery('.repeatingSection').length;
var newCount = currentCount+1;
var lastRepeatingGroup = jQuery('.repeatingSection').last();
var newSection = lastRepeatingGroup.clone(false).find('.cloneButton').remove().end();
newSection.insertAfter(lastRepeatingGroup);
newSection.find("input").each(function (index, input) {
input.id = input.id.replace("_" + currentCount, "_" + newCount);
input.name = input.name.replace("_" + currentCount, "_" + newCount);
});
newSection.find("label").each(function (index, label) {
var l = jQuery(label);
l.attr('for', l.attr('for').replace("_" + currentCount, "_" + newCount));
});
return false;
});
jQuery(document.body).on('click','.removeButton', function(){
jQuery(this).closest('div.repeatingSection').remove();
return false;
});
PHP :
$poste1 = '';
$date1 = '';
$poste1 = trim($_POST['poste_1']);
$date1 = trim($_POST['date_1']);
I know I would need to put them in an array and loop through them but I'm not sure how to go about it.
You can use a for loop and a count variable from javascript and do something like :
for($i=1; $i<$currentCount; $i++) {
${"poste".$i} = trim($_POST["poste_$i"]);
${"date".$i} = trim($_POST["date_$i"]);
}
You would have variables $poste1 and $date1. Using ${''} creates dynamic variables.
I have a page that has three checkbox lists, the three are dynamically generated
what I want and that as the User is clicking the checkbox values are passed via post, but I only managed to catch Esto values of the first list
I did the code like this:
$("body").find(".fcID").click(function(){
// var v = $(this).val();
//alert(v);
var form = jQuery('#form');
valor = form.serialize();
$.ajax({
type : "POST",
url:"biblioteca/filtra.php",
data: valor,
success: function(data){
$("#tabelafiltro").html(data);
}
});
in html, I put a form with the id of her form and name the form
within that form, I have the checkboxes, so:
<form name="form" id="form" action="" method="post">
<table>
<tr>
<td><input type="checkbox" class="fcID" value="<?php echo $linha['fm-cod-com'] ?>" name="fcID[]"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="checkbox" class="fcID" name="fam[]" value="<?php echo $linha['fm-codigo'] ?>" /></td>
</tr>
</table>
</form>
and the php:
$id = $_POST['fcID'];
$fam = $_POST['fam'];
echo(count($fam)) . " + " . count($id);
somebody help me?
Your code is correct, are u sure that the fam[] checkboxes are checked? Checkboxes will serialize only if they have atribute checked="checked".
Unfortunately the "name" is not converted to an array by jQuery.. so instead of this:
echo $_POST['fcID'][0]; // undefined
you have this
echo $_POST['fcID[]']; // expected value
I created the following. It has some limitations, but should do what you want. I appreciate if you can rate my answer.
var form = jQuery('#form');
valor = form.formToObj();
// formToObj (c) 2012 Frank Forte.
// Please contact me for a free license to use on personal or business website
// #frankforte or frank # interactinet .com!
jQuery.fn.formToObj = function()
{
var obj = {}
jQuery("input,select,textarea",this).each(function(){
if(jQuery(this).attr("disabled")){
return;
}
var n = jQuery(this).attr("name") || jQuery(this).attr("id")
var v = jQuery(this).val();
// e.g.<input name="test[one][two][three]" value="hello world">
if(!n.match(/\[/))
{
obj[n] = v
}
else
{
// get keys of array, e.g. "one","two","three"
var keys = []
nkeys= n.split('[')
var i = 0;
for(k in nkeys)
{
if(i > 0)
{
var nk = nkeys[k]
if(typeof nk == "string")
{
if(nk.match(/\]/))
{
nk = nk.replace("]","")
}
keys.push(nk);
}
}
i++
}
// name e.g. "test"
n = n.replace(/^([^\[\]]+)\[.*$/i,"$1");
// create object and add value then array keys from bottom up
var iobj = {}
for(i = keys.length; i > 0; i--)
{
j = i-1;
var k = keys[j]
if(k==""){k = 0;}
if(i == keys.length)
{
iobj[k] = v
}
else
{
iobj[k] = iobj
}
}
// Need to start with obj[n] and add new values under appropriate keys
// prevents unsetting or overwriting keys deeper than n
if(typeof obj[n] == "undefined")
{
obj[n] = {}
}
obj[n][k] = iobj[k]
}
})
return obj
}
Here's the issue: I have a JS dropdown for country and state that runs in a PHP form for users to update their profiles.
The user selects country for ex 'USA', then state 'Colorado', and submits. What happens is that these values are saved OK on my database, but when the page refreshes, only the country dropdown remains selected with the user's choice. The state shows as 'Select State', although the value 'Colorado' is in the DB.
I just can't manage to have PHP and JS talk to each other so that if the user chose Colorado, it should be pulled from the DB and shown as selected whenever they refresh or come back to the page.
Any ideas how to do this? I tried the suggestion at the top of the JS code but was unsuccessful.
Here is the JS (some code trimmed for brevity):
// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = '';
var postCountry = '';
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:Alaska:Alaska|\
US:Alabama:Alabama|\
';
var country = '\
US:United States|\
CA:Canada|\
';
function TrimString(sInString) {
if ( sInString ) {
sInString = sInString.replace( /^\s+/g, "" );// strip leading
return sInString.replace( /\s+$/g, "" );// strip trailing
}
}
// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
if ( postCountry != '' ) {
defaultCountry = postCountry;
}
var countryLineArray = country.split('|'); // Split into lines
var selObj = document.getElementById('countrySelect');
selObj.options[0] = new Option('Select Country','');
selObj.selectedIndex = 0;
for (var loop = 0; loop < countryLineArray.length; loop++) {
lineArray = countryLineArray[loop].split(':');
countryCode = TrimString(lineArray[0]);
countryName = TrimString(lineArray[1]);
if ( countryCode != '' ) {
selObj.options[loop + 1] = new Option(countryName, countryCode);
}
if ( defaultCountry == countryCode ) {
selObj.selectedIndex = loop + 1;
}
}
}
function populateState() {
var selObj = document.getElementById('stateSelect');
var foundState = false;
// Empty options just in case new drop down is shorter
if ( selObj.type == 'select-one' ) {
for (var i = 0; i < selObj.options.length; i++) {
selObj.options[i] = null;
}
selObj.options.length=null;
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
// Populate the drop down with states from the selected country
var stateLineArray = state.split("|"); // Split into lines
var optionCntr = 1;
for (var loop = 0; loop < stateLineArray.length; loop++) {
lineArray = stateLineArray[loop].split(":");
countryCode = TrimString(lineArray[0]);
stateCode = TrimString(lineArray[1]);
stateName = TrimString(lineArray[2]);
if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
// If it's a input element, change it to a select
if ( selObj.type == 'text' ) {
parentObj = document.getElementById('stateSelect').parentNode;
parentObj.removeChild(selObj);
var inputSel = document.createElement("SELECT");
inputSel.setAttribute("name","state");
inputSel.setAttribute("id","stateSelect");
parentObj.appendChild(inputSel) ;
selObj = document.getElementById('stateSelect');
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
if ( stateCode != '' ) {
selObj.options[optionCntr] = new Option(stateName, stateCode);
}
// See if it's selected from a previous post
if ( stateCode == postState && countryCode == postCountry ) {
selObj.selectedIndex = optionCntr;
}
foundState = true;
optionCntr++
}
}
// If the country has no states, change the select to a text box
if ( ! foundState ) {
parentObj = document.getElementById('stateSelect').parentNode;
parentObj.removeChild(selObj);
// Create the Input Field
var inputEl = document.createElement("INPUT");
inputEl.setAttribute("id", "stateSelect");
inputEl.setAttribute("type", "text");
inputEl.setAttribute("name", "state");
inputEl.setAttribute("size", 30);
inputEl.setAttribute("value", postState);
parentObj.appendChild(inputEl) ;
}
}
function initCountry(country) {
populateCountry(country);
populateState();
}
and here is the PHP/HTML (trimmed a bit):
<?php
include 'dbc.php';
page_protect();
$err = array();
$msg = array();
if ($_POST['doUpdate'] == 'Update') {
foreach ($_POST as $key => $value) {
$data[$key] = filter($value);
}
$country = $data['country'];
$state = $data['state'];
mysql_query("UPDATE users SET
`country` = '$data[country]',
`state` = '$data[state]'
WHERE id='$_SESSION[user_id]'
") or die(mysql_error());
$msg[] = "Your Profile has been updated";
//header("Location: mysettings.php?msg=Your new password is updated");
}
$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
?>
<html>
<body>
<form name="profile_form" id="profile_form" method="post" action="">
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
<input name="doUpdate" type="submit" id="doUpdate" value="Update">
<table>
<tr>
<th>Country:</th>
<td><select id='countrySelect' name='country' onchange='populateState()'>
</select></td>
</tr>
<tr>
<th>State:</th>
<td>
<select id='stateSelect' name='state'>
</select>
<script type="text/javascript">
initCountry('<?php echo $row_settings['country']; ?>');
</script>
</td>
</tr>
</table>
</form>
</body>
</html>
One of the issues i often run into with Javascript is the load order.
You appear to be running and calling populateCountry and populateState at the same time, thereby not having much opportunity for the State list to be populated once the country list has been determined.
Consider moving "populateState()" to the last line of "populateCountry()" so it calls it at the end of the function processing.
There are multiple ways to do this, but this is the simplest to illustrate the point.
Change the top lines
// If you have PHP you can set the post values like this
//var postState = '<?php echo $_POST["state"] ?>';
//var postCountry = '<?php echo $_POST["country"] ?>';
var postState = '';
var postCountry = '';
to
// If you have PHP you can set the post values like this
var postState = '<?= $_POST["state"] ?>';
var postCountry = '<?= $_POST["country"] ?>';
//var postState = '';
//var postCountry = '';
Does that not work?
PHP Short tags, ie "<?=" are not enabled by default anymore i believe in some of the newer php versions. I've stopped using it, i know it looks pretty but it can be a pain if you migrate to a server that doesn't support them.
<form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
document.write(
'<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
'Show the password as I type'
);
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
(kc >= 97 && kc <= 122 && sk) ||
(kc >= 65 && kc <= 90 && !sk)
) {
document.getElementById('capsalert').style.display = 'inline';
}
else {
document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
I'm using the above code in a slightly more complex form.
I have two separate "password" fields on the form. With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.
Also, the code notifies the user if they are typing with CAPS Lock enabled.
I would like to have both password fields exhibiting the same behavior rather than the first field only. Unfortunately, I do not know how to make that happen.
Thanks for the help.
EDIT:
A simple solution might be easier to find with the following code. I'm willing to use either one.
<script>
function changeType()
{
document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>
<body>
<form name="myform">
<input type="password" name="pass" />
<input type="password" name="pass2" />
<input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
Why don't you just change the type attribute of the password inputs in your unmask() function? That way it will be easier for you to manage more than 1 field. After checking whether you have to turn the input into a text one or a password one, do this:
// Suppose 'new_type' is either 'text' or 'password'
// and that 'pwd' and 'pwd2' are the id attributes for
// both of your password fields
document.getElementById('pwd').type = new_type;
document.getElementById('pwd2').type = new_type;
I suggest changing your approach a bit.
You could modify the client with no impact to the server code. For example, I would try using 2 input boxes with the same name. If you ever have one box visible while the other one has the 'disabled' HTML attribute set, the visible box will always be the only one submitted.
This way, your server-side code would only have to look for 1 input, under a single name.
jQuery caps lock test/function?
set both fields to class of password and:
jQuery('.password').caps(function(caps){
if(jQuery.browser.safari) return; // Safari already indicates caps lock
// "this" is current element
if(caps){
alert('Your caps lock is on!');
}else{
// no caps lock on
}
});
Try this:
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !! (ev.modifiers & 4) : false));
if ((kc >= 97 && kc <= 122 && sk) || (kc >= 65 && kc <= 90 && !sk)) {
document.getElementById('capsalert').style.display = 'inline';
} else {
document.getElementById('capsalert').style.display = 'none';
}
//end if
}
//end function
function unmask(truefalse) {
for (var f in new Array('pwd', 'pwd2')) {
oldElem = document.getElementById(f);
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById(f).value);
elem.id = f;
oldElem.parentNode.replaceChild(elem, oldElem);
document.getElementById(f).onkeypress = function (e) {
chkCaps(e);
};
}
}
//end function
document.getElementById('pwd').onkeypress = function (e) {
chkCaps(e);
};
document.getElementById('pwd2').onkeypress = function (e) {
chkCaps(e);
};
What this does is make it so your code works on pwd and pwd2 by repeating it for each element in the array new Array('pwd', 'pwd2').
Most of the answers didn't work. One or two I left untried because they meant greater changes to my code than I wanted. I ended up finding yet another method to reveal the passwords: "Show password as text" control
I adapted the method there to my multiple password fields scenario:
<input type="checkbox" onchange="document.getElementById('gpwd').type = this.checked ? 'text' : 'password'; document.getElementById('pwd1').type = this.checked ? 'text' : 'password'; document.getElementById('pwd2').type = this.checked ? 'text' : 'password'"> Reveal passwords