Simple HTML DOM help - php

How can I extract the value attribute of an input tag? Using SIMPLE HTML DOM
let me give you an example:
<form action="#" method="post" name="test_form" id="test_form">
Name<input type="text" name="name" value="NaMe"/><br />
Address<input type="text" name="address" value="AdDrEsS"/><br />
<input type="hidden" value="sayantest" />
</form>
I want to extract just the value of hidden type input tag, not the others.

You want to put the id (so you can access the value in javascript), as well as a name (if you want to access the value on the server) in the tag you wish to get the value from.
e.g.
<input type="hidden" name="test" id="test" value="sayantest" />
then your javascript is as simple as:
<script type="text/javascript">
var val = document.getElementById('test').value;
alert(val);
</script>

using SIMPLE HTML DOM
Do you mean the PHP library of that name?
If so, you'd have to choose a way to identify the input. If you can't change the markup to add an id or name on the hidden input you want, you'd have to come up with something like “get the first input with type hidden in the form”:
$html= new simple_html_dom();
$html->load('<html><body<form action="#" method="post" name="test_form" id="test_form">Name<input type="text" name="name" value="NaMe"/><br />Address<input type="text" name="address" value="AdDrEsS"/><br /><input type="hidden" value="sayantest" /></form></body></html>');
$input= $html->find('#test_form input[type=hidden]', 0);
$input->value;

The easiest way, as already mentioned, is to give your hidden input an id attribute and then use getElementById and then .value or .getAttribute('value') to select it.
Alternatively, if you want to get the values of all hidden inputs on the page, or can't inject your ID, you could use something like this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].getAttribute('type') == 'hidden'){
alert(inputs[i].getAttribute('value'));
}
}

Here is what I came up with... using exactly what you showed in your initial question. Note that all I did was echo the value of all input hidden, where test_form.htm is your original:
<?php
function scraping_form()
{
// create HTML DOM
$html = file_get_html('test_form.htm');
// get input hidden value
$aObj = $html->find('input[type="hidden"]');
foreach ($aObj as $hKey=>$hidden)
{
$valueAttribute = $hidden->value;
echo "*TEST* ".$hKey.": ".$valueAttribute."<br />";
}
// clean up memory
$html->clear();
unset($html);
return;
}
// -----------------------------------------------------------------------------
// test it!
// user_agent header...
ini_set('user_agent', 'My-Application/2.5');
scraping_form();
?>

Related

How to access form element xyz[] in Javascript?

I have code that will automatically add a new similar row defined in form by clicking add button.
<html>
<body>
<form>
<input type="text" name="quantity[]" class="input_text" id="pro"/>
</form>
</body>
</html>
Now I want to access different values of quantity[] in javascript function .
How to access this different values of quantity[] in javascript using it's ID or Name Attribute.
<script>
function abc() {
var id = document.getElementById("pro").value;
}
</script>
You can do something like this.
html:
<form>
<input name="p_id[]" value="0"/>
<input name="p_id[]" value="1"/>
<input name="p_id[]" value="2"/>
</form>
javascript:
var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
alert(p_ids[i].value);
}
The way to do that with plain JavaScript is to get all the elements with an specific name, as following:
var fields = document.getElementsByName('quantity[]');
Should you want to access an specific value, you could do that as well:
console.log(fields[0].value); // foo
Here's a jsfiddle with a code sample.
HTML:
<form name="order">
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
</form>
JS:
var elements = document.forms['order'].elements['quantity[]'];
console.log(elements[1].value); // outputs the value of the 2nd element.
demo: http://jsfiddle.net/NDbwt/
$('input[name=quantity]').each(function(){
alert($(this).val())
});
First: id must be unique on page. Otherwise document.getElementById will always return first spotted element with requested id.
In your case, you may do next:
var id = document.getElementsByName("quantity[]")[0].value;
But more safely (I'm not sure if order of items in returned array will always be the same as order in which elements are added) would be to generate ids like pro_0, pro_1, pro_2 etc
You're probably confused by the fact that PHP reads form fields as arrays when you use square brackets on their name. That's only a PHP trick—for JavaScript, [] does not have any special meaning and you can read the items in the usual way:
var values = [];
var fields = document.getElementsByName("quantity[]");
for (var i = 0, len = fields.length; i < len; i++) {
values.push(fields[i].value);
}
alert("Values:\n" + values.join("\n"));
See it in action.

How To Add ucwords() in PHP To HTML Form Value?

I have a basic contact form on my website and I am trying to add the PHP ucwords() function of PHP to the form for the users first_name and last_name fields so they capitalize the first letter correctly. How would I add this to the actual HTML form?
Edit: I want these changes to be applied only after the user submits the form. I don't really care about how the user types it in. I just need someone to actually show me an example.
Like how would I add the PHP ucwords() code to this simple form?
<!DOCTYPE html>
<html>
<body>
<form action="www.mysite.com" method="post">
First name: <input type="text" name="first_name" value="" /><br />
Last name: <input type="text" name="last_name" value="" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I am assuming I do something like value='<php echo ucwords() ?>' but I have no idea how?
Thanks!
When user submit the form you can access the submitted information through $_POST variable [because method="post"] of PHP and in action you have to specify the actual page where you need the submitted information to be process further
<?php
// for example action="signup_process.php" and method="post"
// and input fields submitted are "first_name", "last_name"
// then u can access information like this on page "signup_process.php"
// ucwords() is used to capitalize the first letter
// of each submit input field information
$first_name = ucwords($_POST["first_name"]);
$last_name = ucwords($_POST["last_name"]);
?>
PHP Tutorials
Assuming short tags are enabled:
$firstName = 'Text to go into the form';
<input type="text" name="first_name" value="<?=ucwords($firstName)?>" />
Otherwise as you stated
<input type="text" name="first_name" value="<?php echo ucwords($firstName); ?>" />
Assuming you wanted to do it without a page refresh, you need to use Javascript. Simplest way would be to add an onkeyup event to the input field and simulate PHP's ucwords functions, which would look something like...
function ucwords(str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
Edit: In response to your edit, if you want to get the value they sent with ucwords applied, all you need to do is $newVal = ucwords($_POST['fieldName']);

Change the value of multiple dynamically PHP generated text-boxes using jquery

I have generated multiple text boxes using PHP with name="student[<?php echo $StudentID ; ?>]".
Now on a button click i want to change the value of all these text boxes using jquery.
How do i do this ? Please help.
You can use the Attribute Starts With selector, to look for student[ at the beginning of the name attribute:
$('input[name^="student["]').val('the new value');
It's probably unnecessary to include the [ at the end, and name^="student" will be sufficient, assuming you don't have other inputs with names like student_name or the like.
// If no conflicting named inputs, use
$('input[name^="student"]').val('the new value');
HTML
<input type="text" name="student[]"></input>
<input type="text" name="student[]"></input>
<input type="text" name="student[]"></input>
<button id="button">Change</button>
JavaScript
$('#button').click(function() {
$('input[name^="student"]').val('some value ');
});
JSFiddle
You can also simply add a class that is unique to all of those text boxes (i.e. changableTextBox) and then select it with that and change them all at once. It's also helpful for the future if you need to adjust some styling on all of them at once. Just declare that class in CSS and you're styling.
<input type="text" class="changeableStudentTextBox" id="student[11]" />
<input type="text" class="changeableStudentTextBox" id="student[23]" />
<input type="text" class="changeableStudentTextBox" id="student[45]" />
<input type="text" class="changeableStudentTextBox" id="student[66]" />
<script type="text/javascript">
$('#button').click( function() { $('.changeableStudentTextBox').val('hi!'); });
</script>

Deleting value="Comment?" as soon as it is clicked from the input box

I created an input box and says "comments?" before the user enters anything in it.Code;
<input type="text" name="saysome" value = "comments?"/>
But, i want to delete this "comments?" as soon as it is clicked.I am trying to do input box just like the search box in here, actually exaclty same. How can i do that?Can it be done by only javascipt? :(
Thanks
You can use the html5 placeholder attribute found here:
HTML5 Specs
For example:
<input type="text" name="saysome" placeholder = "comments?"/>
You could also take a javascript approach for browsers that do not support HTML5.
Simple method that will clear it anytime the box has focus, and not if the user has entered anything into it
<input type="text" name="TB" value="Please Enter.." onfocus="this.value==this.defaultValue?this.value='':null"/>
As other commenters mentioned, you should check out placeholder. To answer your question though, this method will remove the text on mouse click if the user has not already entered something. This assumes that the id of the input is textbox. You will have to change it to whatever you have or else assign the input an id.
<input id="textbox" type="text"/>
and the JS:
document.getElementById('textbox').onclick = function()
{
var box = document.getElementById('textbox');
if(box.value==box.defaulValue)box.value =='';
}
<input type="text" name="saysome" onblur="if(this.value=='') this.value='comments?';" onclick="this.value=''" value="comments?" />
See this example # http://x.co/Z2pa
Non-jquery:
onClick="clearComments()"
function clearComments() {
commentInput = document.getElementById("commentsId");
if(commentInput.value == 'comments?') {
commentInput.value = '';
}
}
Without jQuery:
Give the input an ID, and clear its value using an onclick event.
<input type="text" name="test" id="test" value="test" onclick="if(document.getElementById('test').value=='test')document.getElementById('test').value='';">
Also supports older browsers that don't use HTML 5.

Allow user to create and submit up to 5 text boxes with jquery, and parse them into one array in php?

Is it possible?
I want a user to post an array full of 1-5 pieces of data.
At first there would be only one text field on show, but on clicking a 'plus' icon next to it, it would create another text field below it for more user input.
I would also want to have a delete icon next to text boxes 2-5, to remove them if necessary.
My JQuery knowledge is limited, and I can work out how to append text boxes to a list, but not to keep track of them/delete them. Ideally I would also want to pass them as an array to php, so I can easily loop through them.
<input type="text" size="15" maxlength="15" name="1"><img src="add.png" onclick="add();">
<!-- Below is hidden by default, and each one shows on click of the add image -->
<input type="text" size="15" maxlength="15" name="2"><img src="delete.png" onclick="delete(2);">
<input type="text" size="15" maxlength="15" name="3"><img src="delete.png" onclick="delete(3);">
<input type="text" size="15" maxlength="15" name="4"><img src="delete.png" onclick="delete(4);">
<input type="text" size="15" maxlength="15" name="5"><img src="delete.png" onclick="delete(5);">
jQuery clone() is very handy for this. A small example how it could be done (working example on jsfiddle)
<ul>
<li><input type="text" name="textbox[]" /></li>
</ul>
<input type="button" id="addTextbox" value="Add textbox" />
<script type="text/javascript">
$(function(){
$('#addTextbox').click(function(){
var li = $('ul li:first').clone().appendTo($('ul'));
// empty the value if something is already filled in the cloned copy
li.children('input').val('');
li.append($('<button />').click(function(){
li.remove();
// don't need to check how many there are, since it will be less than 5.
$('#addTextbox').attr('disabled',false);
}).text('Remove'));
// disable button if its the 5th that was added
if ($('ul').children().length==5){
$(this).attr('disabled',true);
}
});
});
</script>
For the server-side part, you could then do a foreach() loop through the $_POST['textbox']
As long as you give each text box a name like "my_input[]", then when the form is submitted, PHP can get the answer(s) as an array.
$_REQUEST['my_input']; would be an array of the values stored in each text box.
Source: Add and Remove items with jQuery
Add
Remove
<p><input type="text" value="1" /></p>
<script type="text/javascript">
$(function() { // when document has loaded
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});
$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});
$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});
});
</script>
You will need to create DOM elements dynamically. See how it is done for example in this question. Notice that
document.createElement
is faster then using jquery's syntax like
$('<div></div>')
Using that technick, you could create inputs like
<input name="id1"/>
<input name="id2"/>
<input name="id3"/>
<input name="id4"/>
<input name="id5"/>
On submitting your form you'll get all them in your query string like
...id1=someval1&id2=someval2&...
Having that, you could process this query as you want on server side.
<form method="POST" id="myform">
<input />
Add textbox
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#add_textbox').click(function(){
var form=$(this).closest('form');
var count=form.find('input').length();
form.append('<div class="removable_textbox"><input />delete</div>');
$('.delete_input').click(function(){
$(this).find('.removable_textbox').remove();
return false;
});
return false;
});
$('#myform').submit(function(){
var i=1;
$(this).find('input').each(function(){
$(this).attr('name','input-'+i);
i++;
})
});
});
</script>
<?php
if(isset($_POST['input-1'])){
$input_array=$_POST;
}
?>
something like this?
I wrote a litte jQuery plugin called textbox. You can find it here: http://jsfiddle.net/mkuklis/pQyYy/2/
You can initialize it on the form element like this:
$('#form').textbox({
maxNum: 5,
values: ["test1"],
name: "textbox",
onSubmit: function(data) {
// do something with form data
}
});
the settings are optional and they indicate:
maxNum - the max number of elements rendered on the screen
values - an array of initial values (you can use this to pass initial values which for example could come from server)
name - the name of the input text field
onSubmit - onSubmit callback executed when save button is clicked. The passed data parameter holds serialized form data.
The plugin is not perfect but it could be a good start.

Categories