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.
Related
I have a text field on my form actually its like GMT time. I want the users to
enter integers like '+5' '+6' or '-6' or '-5' etc.
I want to make it easy for users so that they don't have to write '+' or '-' by there self. There should be by default option of '+' or '-' as first character in text field.
I saw some solutions like making a simple drop down in front and user can select from there which will automatically appear in text box.
But i want to make it more easy if some other easy solution is there.
will prefer using HTML5 but if not than jquery will be fine..
Try this one:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var num = 0;
$('#txt1').keydown(function(e){
num += 1;
if (e.keyCode > 36 && e.keyCode < 41) {
if(num % 2){
$('#txt1').val('+');
}else{
$('#txt1').val('-');
}
}
});
});
</script>
<input type="text" name="txt1" id="txt1" />
you could try this:
var $input = $('#input');
var defaultChar = '+';
$input.val(defaultChar);
$input.on('keyup', function(event) {
var $this = $(this);
var currentText = $this.val();
currentText = getDigits(currentText);
$this.val(defaultChar + currentText);
});
function getDigits(text) {
var digits = text.match(/[+-]?(\d*)/);
console.log("text = " + text);
console.log("digits = " + JSON.stringify(digits));
if(digits.length > 1) {
return digits[1];
} else {
return 'did not contain numbers';
}
}
here is the fiddle
EDIT: added dropdown to select defaultChar.
Javascript:
var $input = $('#input');
var $defaultCharElem = $('#defaultChar');
var defaultChar = $defaultCharElem.val();
$input.val(defaultChar);
$defaultCharElem.on('change', function() {
var $this = $(this);
defaultChar = $this.val();
$input.val(defaultChar + getDigits($input.val()));
});
$input.on('keyup', function(event) {
var $this = $(this);
var currentText = $this.val();
currentText = getDigits(currentText);
$this.val(defaultChar + currentText);
});
function getDigits(text) {
var digits = text.match(/[+-]?(\d*)/);
console.log("text = " + text);
console.log("digits = " + JSON.stringify(digits));
if(digits.length > 1) {
return digits[1];
} else {
return 'did not contain numbers';
}
}
HTML:
<select id="defaultChar">
<option value="+">+</option>
<option value="-">-</option>
</select>
<input type="text" id="input" value="" />
Here is the new fiddle
I found many examples of this getting data from a mysql query. What I want to pass back to jQuery function is parsed html content in JSON format. What I want to do is separate PHP code from my initial load of the page. I'm doing this in jQuery Mobile. I know, my description is bad, it's hard to phrase.
I get article names and links from my database and output listview in index.html. When the user clicks on an article, I'm passing the link in the URL, getting it in jQuery and trying to call a PHP file which Parses that URL. Here's ALL the code:
index.html:
<body>
<div data-role="page" id="mainNews">
<div data-role="content">
<ul id="fnews" data-role="listview"></ul>
</div>
</div>
<script src="js/getmainnews.js"></script>
</body>
getmainnews.js:
var serviceURL = "http://localhost/basket/services/";
var news;
$('#mainNews').bind('pageinit', function(event) {
getNews();
});
function getNews() {
$.getJSON(serviceURL + 'getmainnews.php', function(data) {
$('#fnews li').remove();
mainnews = data.items;
$.each(mainnews, function(index, mnews) {
$('#fnews').append('<li data-icon="false"><a style="white-space:normal;" href="newstext.html?url=http://www.basket-planet.com' + mnews.link + '">' + mnews.article + '</a></li>');
});
$('#fnews').listview('refresh');
});
}
getmainnews.php:
<?php
include 'connect_to_mysql.php';
mysql_query("SET NAMES UTF8");
$sql = mysql_query("SELECT * FROM basket_news");
$mainnews = array();
while ($r = mysql_fetch_assoc($sql)){
$mainnews[] = $r;
}
echo '{"items":'. json_encode($mainnews).'}';
?>
Everything loads fine but the next page comes up empty. Here's the next 3 files...Sorry that this is such a long topic.
newstext.html:
<body>
<div data-role="page" id="newstext">
<div data-role="content">
<div id="textcontent"></div>
</div>
</div>
</body>
newstext.js:
var serviceURL = "http://localhost/basket/services/";
$('#newstext').bind('pageshow', function(event) {
var url = getUrlVars()["url"];
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
});
function displayNewsText(data){
var newstext = data.item;
$('#textcontent').append(newstext);
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
And finally getnewstext.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$html = file_get_html(''.$url.'');
$article = $html->find('div[class=newsItem]');
$a = str_get_html(implode("\n", (array)$article));
#$a->find('div[style*=float]', 0)->outertext = '';
#$a->find('h3', 0)->outertext = '';
#$a->find('div[id=comments]', 0)->outertext = '';
#$a->find('script', 0)->outertext = '';
#$a->find('a[href*=register]', 0)->outertext = '';
#$a->find('div', 4)->outertext = '';
#$a->find('div', 6)->outertext = '';
echo '{"item":'. json_encode($a) .'}';
?>
So those are the 6 files. On the newstext.html, the URL contains the URL which I need to pass to my PHP file. I'm sure the problem is in the last three files. What am I doing wrong here? Thanks in advance!
Update: Console error fixed, but still no output on the page.
Update2: From searching around, I saw somewhere that json_encode only accepts arrays. My $a in last PHP script is content from a page containing all kinds of html tags. How can I turn this into an array? To make one key/value with the value being all that html content?
The error getUrlVars is not defined newstext.js:3 says it all. You are calling a function that is not defined anywhere. I did a quick search and you probably want this:
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
below is my simple code using HTML 5 multiple file upload. All i need is to grab all the file names not the paths below is simple javascript code
function getFileNames()
{
var path = $('#files').val();
console.log(' path = ' + path);
}
and html form is as
<form action='server.php' method='post' enctype='multipart/form-data' target="iframe">
<input id="files" name='files[]' type='file' multiple>
<input type='button' onclick="getFileNames()">
</form>
when i press the button the console output is as
path = Chrysanthemum.jpg
which is the first name of the file and i want the remaining names , any suggestions , comments are appreciated.
thanks.
well so here i am with the solution after lot of research, in case of input type file the value is stored in array as files with key name.
var files = $('input#files')[0].files;
var names = "";
$.each(files,function(i, file){
names += file.name + " ";
});
alert(names);
fiddle : http://jsfiddle.net/raj_er04/nze2B/1/
pure javascript
function getFileNames(){
var files = document.getElementById("files").files;
var names = "";
for(var i = 0; i < files.length; i++)
names += files[i].name + " ";
alert(names);
}
fiddle : http://jsfiddle.net/raj_er04/nze2B/2/
function getFileNames()
{
var files = document.getElementById("files").files;
for (var i = 0, f; f = files[i]; i++) {
console.log(' name= ' + f.name);
alert(' path = ' + f.name);
}
}
Instead of
var path = $('#files').val();
loop through the array, use
var names = "";
var path = $('#files').each(function(i, el) {
names = names + el.val() + ",";
});
$(document).ready(function(){
var skillctr = 1;
var experiencectr = 1;
var educationctr = 1;
var achievementctr = 1;
var historyctr = 1;
/*
Add Skills
*/
$("#addSkill").click(function () {
if(skillctr>10){
alert("WOW! But 10 skills are enough.");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'SkillDiv' + skillctr);
newTextBoxDiv.html('<label>Skill No. '+ skillctr + ' : </label>' +
'<input type="text" name="skill' + skillctr +
'" id="skill' + skillctr + '" value="" >');
newTextBoxDiv.appendTo("#SkillsBoxesGroup");
skillctr++;
});
so how can i save the generated fields in my table in database now?
how am i gonna declare the field in php like.. $_POST['skill'].
i need help here. please
Don't use name="skill' + skillctr + '", use name="skill[]".
That way PHP will helpfully create an array that you can loop though:
var_dump($_POST);
foreach ($_POST['skill'] as $skill) {
// save $skill to database
}
You just need to make sure that the input elements you are adding with that javascript are inside a <form>. Then when you submit the form to a php page, you can access the values with $_POST like you wrote above.
The invoice input values which hold the totals of invoice line items that get updated via JS return a NULL value when they are submitted.
<span class="sublabel">Subtotal</span><input type="text" class="total-box" id="product-subtotal" readonly="true" />
<span class="sublabel">Tax</span><input type="text" class="total-box" id="product-tax" readonly="true" />
<span class="sublabel">Total</span><input type="text" class="total-box" id="order-total" readonly="true" />
The JS
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function(){
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(prodSubTotal);
};
function calcTaxTotal() {
var taxTotal = 0;
//var taxAmount = 10;
var taxAmount = $("#salesTaxAmount").val() || 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var taxTotal = parseInt(productSubtotal) * parseInt(taxAmount) / 100;
var taxTotalNice = taxTotal;
$("#product-tax").val(taxTotalNice);
};
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var productTax = $("#product-tax").val() || 0;
var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
var orderTotalNice = "$" + orderTotal;
$("#order-total").val(orderTotalNice);
};
$(function(){
$('.row-total-input').each(
function( intIndex ){
$('.invAmount').livequery('blur', function() {
var $this = $(this);
var amount = $this.val();
var qty = $this.parent().find('.invQty').val();
if ( (IsNumeric(amount)) && (amount != '') ) {
var rowTotal = qty * amount;
$this.css("background-color", "white").parent().find(".row-total-input").val(rowTotal);
} else {
$this.css("background-color", "#ffdcdc");
};
calcProdSubTotal();
calcTaxTotal()
calcOrderTotal();
});
}
);
});
I originally had the inputs set as disabled however I have changed them to readonly because disabled fields can't be submitted.
What am i missing?
Thanks in advance.
You haven't set a name-attribute on your <input />s, so PHP can't access their values, and returns nothing when you look for $_POST['product-tax']. If you have set error_reporting to E_ALL, you should see a notice telling you you are trying to access an undefined index on the $_POST array.