Form that removes WWW. and prints result on input? - php

I need to make a form similar to the one "shorten link" sites use. It should simply remove WWW. and echo the result so I later add my code around it.
For example if the user types www.pizza.com/blablabla clicking on input should display: pizza.com/blablabla
Thanks

You can do lots of fancy stuff with regular expressions. For example, this javascript will do what you want:
// Event for enter click
$("#url").keypress(
function(e) {
if(e.keyCode == 13) {
$("#output").html(cleanURL($("#url").val()));
}
}
);
// Event for button click
$("#submit").click(
function() {
$("#output").html(cleanURL($("#url").val()));
}
);
// Function to clean url
function cleanURL(url)
{
if(url.match(/http:\/\//))
{
url = url.substring(7);
}
if(url.match(/^www\./))
{
url = url.substring(4);
}
return url;
}
Works on enter click, button click and removes both http:// and www
You can try it out here: http://jsfiddle.net/Codemonkey/ydwAb/1/

Related

Javascript confirm & while looped echo

I have a small problem, I made a delete button with a PHP while loop which looks like this:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<button onclick="delconfirm()">Delete</button>
}
this echo's a few delete buttons for some content. However I need user confirmation for deleting first, this is where onclick="delconfirm()" comes in.
my confirm looks like this:
function delconfirm()
{
var r=confirm("Are you sure you want to delete this content?");
if (r==true){
// ...do nothing i guess? it needs to redirect using the PHP echo'd link...
}
else{
window.location = "edit.php";
}
}
However, whether you press cancel or ok, it'll delete it anyway. How can I fix this?
Change it to this:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<button onclick="return delconfirm();">Delete</button>
}
And then your function:
function delconfirm()
{
return confirm("Are you sure you want to delete this content?");
}
EDIT: If you want a more unobtrusive solution:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<input type="button" value="Delete" data-id="$id" />';
}
And then some javascript to bind the event:
function bindButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].type == "button") {
buttons[i].onclick = function () {
location.href='somewhere.php?id=' + this.getAttribute("data-id");
}
}
}
}
and bind it to the window.onload, as per Ian suggestion:
window.onload = bindButtons;
Note: If you were using jQuery this solution would be easier and more elegant.
Working jsFiddle
If the user presses cancel then you need to stop the event from doing what it would normally do. Try this, for example:
function delconfirm(e) {
e = e || window.event;
if (!confirm("Are you sure you want to delete this content?")) {
e.preventDefault();
// This will prevent the event from bubbling up to the <a>.
e.stopPropagation();
return false; // For the ancient/crappy browsers still out there.
}
return true;
}
You need to stop/delete the current click event. After your code is executed the event sinks to the anchor and triggers a click. With MooTools just add 'new Event().stop();'. I think jQuery has also something like this.
EDIT: Hanlet EscaƱo is right. You can return true (the browser will redirect to the URL in the href, or false to let the browser do nothing)
In order to prevent to the HTML link to work, you have to return false in your js function or event.preventDefault() where event is an argument which is passed to the click event function
I did thin when putting a click event on the a element and not on an element inside the a tag. But it might work.

How to refresh a div content when clicking a link without reloading all the page?

In my website authors (users) can mark posts as favorite.
It works this way:
if ($favinfo == NULL || $favinfo == "") {
$favicon = "ADD"; .
}
else {
$favicon = "REMOVE";
}
Its suposed to look dynamic, it works, when user click ADD, it adds the post to his favorites and reload the page with the REMOVE link.
The problem is its not really dynamic it reloads all the page.
How can i only reload that link (wich is inside a div)?
I know i have to use ajax, jquery, etc, but i tried some examples found here in S.O. but no success.
$('a').on('click', function(e){
// the default for a link is to post a page..
// So you can stop the propagation
e.stopPropagation();
});
Including this stop you page from reloading your entire page
If you want it to be dynamic, you will need to use AJAX. jQuery has ajax support which makes this really easy. If you are not familiar with ajax or javascript you should read up on it first.
PHP
if ($favinfo == NULL || $favinfo == "") {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"add\" href=\"".$siteurl."/author/favorites.php"\">ADD</a>"; .
}
else {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"remove\" href=\"".$siteurl."/author/favorites.php"\">REMOVE</a>";
}
JavaScript
$('a.fav-btn').on('click', function(e){
var $this = $(this), // equates to the clicked $('a.fav-btn')
url = $this.attr('href'), // get the url to submit via ajax
id = $this.attr('data-id'), // id of post
action = $this.attr('data-action'); // action to take on server
$.ajax({
url: url+'?'+action+'='+id
}).done(function(){ // once favorites.php?[action]= is done...
// because this is in .done(), the button will update once the server has finished
// if you want the link to change instantly and not wait for server, move this outside of the done function
if(action === 'add'){
$this.attr('data-action', 'remove').html('REMOVE'); // update the button/link
}else{
$this.attr('data-action', 'add').html('ADD');
}
})
return false; // prevent link from working so the page doesn't reload
}
If you are okay with using JQuery, you have some tools to accomplish this.
Have a structure / method of identifying your links.
You can have a click() listener on your add button that will call a JQuery $.post(url, callback) function.
In that callback function, you can have it update the corresponding DIV (that you defined in #1) with a 'remove' link. i.e if you identify the DIV by ID, you can retrieve it via $('#id') and then update that object.
The same idea can apply with the 'remove' link that you add.
So, generally...
<button id="add">Add</button>
<div id="links"> ...</div>
<script>
$('#add').click(function() {
$.post('your url',
function(data) {
var links = $('#links');
// update your links with 'remove' button, etc
}
);
});
</script>

Validate form fields in sequences

I have a multi-step order form built in this manner:
Step 1: Choose category via radio button
The "Next" button is just an image that has an onclick function hides the current div with the radio buttons, and displays a new div with the next step in the process.
Step 2: Textarea, checkbox -> Dynamic price
Contains a textarea, a dynamic price, and four checkboxes. The price changes depending on the number of characters in the textarea and the choices in the checkboxes. JQuery script is used in order to do that. Again, the "Next" button is just an image that upon activating the onclick function hides the current div, and displays the div containing the next step in the form.
Step 3: Personal Data
And here is my problem. Here where the user inserts name, email and so on. The "Next" button is again just an image that upon activating the onclick function hides the current div and displays the div containing the next step. How do i make the form fields in this step required in order to allow the user to advance to the next step. The code i have for hiding and showing the divs is as follows:
<script type="text/javascript">
function toggleDiv(id, flagit) {
if (flagit == "1") {
if (document.layers) document.layers[''+id+''].visibility = "show"
else if (document.all) document.all[''+id+''].style.visibility = "visible"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
}
else`if (flagit == "0") {
if (document.layers) document.layers[''+id+''].visibility = "hide"
else if (document.all) document.all[''+id+''].style.visibility = "hidden"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"`
}
}
//-->
</script>
That is a horrible (and wrong) piece of old code.
here is an update that actually still handles Netscape4 (the layers part)
You need to show me the rest of the script where you toggle. You need to add validation to
THAT part, not the toggle.
For example, using
<form onsubmit="return validate(this)">
and
<input type="image" src="next.png" />
you can do this (plain JavaScript, the show and hide in jQuery is shown elsewhere on the page):
var currentStep=1;
function toggleDiv(id,flagit) {
if (document.getElementById) document.getElementById(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.all) document.all(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.layers) document.layers[id].visibility = (flagit)?"show":"hide";
}
function validate(theForm) {
if (currentStep == 1) {
if (theForm.category.value....) {
alert("Error in category");
return false;
}
currentStep++;
toggleDiv("part1",0);
toggleDiv("part2",1);
return false; // do not submit
}
if (currentStep == 2) {
if (theForm.price.value....) {
alert("Error in price");
return false
}
currentStep++;
toggleDiv("part2",0);
toggleDiv("part3",1);
return false; // do not submit
}
if (currentStep == 3) {
if (theForm.name.value....) {
alert("Error in name");
return false
}
return true; // submit
}
}
Well, since you have tagged your question with jQuery, why not actualy use it and let jquery handle all platform specific issues.
function toggleDiv(id,flagit) {
if( flagit ) {
$("#"+id).show();
} else {
$("#"+id).hide();
}
}
Let me know if this works.

Submit button not working in IE/Safari, works in Chrome but form info is not getting passed

I have a form setup but for some reason the JS to submit the form works in Chrome but not IE9 or Safari. Interestingly enough in Chrome where the submit button does work none of the information gets passed.
Here is my submit button -
<img type="submit" src="lib/send_feedback.jpg" border="0" class="feedback-submit-img" />
Here is what JS it calls
// Submit form to next page
function submitForm() {
// document.forms["feedbackform"].submit();
document.feedbackform.submit();
}
// Submit form and validate email using RFC 2822 standard
function validateEmail(email) {
// Modified version original from: http://stackoverflow.com/a/46181/11236
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
// Return true if email field is left unchanged
function originalText(email){
var defaultMsg;
defaultMsg = "Enter your email address (optional)";
if(defaultMsg == email){
return true;
}
return false;
}
// Verify or decline with error message
function validate(){
$("#result").text("");
var email = $("#email").val();
if ((validateEmail(email)) || originalText(email)) {
submitForm();
} else {
$("#result").text(email + " is not a valid email.");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
For the second part of my issue which may or may not be related to the JS issue is -
echo $POST['satisfaction'];
echo $POST['user_email'];
echo $POST['comments'];
if(isset($POST['user_email'])){
echo 'true';
} else {
echo 'false';
}
If you would like a better look at the page I am editing here is a link to jsfiddle
edit
As per Marco's request I removed the link from around the submit button and placed the onClick event onto the actual button itself. This absolutely fixed the issue on both IE and Safari. Now my remaining question/concern is why the POST data is not passing correctly to the next page.
Here is the complete source with George requested. - index.php
Page source gets passed to - feedback-accept.php
Also with that being said/posted, what is StackOverflow's preferred site to post source to?
In response to Brian's comment, if I cannot use failed without potentially breaking the POST data, what would be a good alternative/work-around?
try this code:
jQuery:
$(document).ready(function()
{
$('.validate').bind('submit click',function()
{
//Validate!
//is email
if( /..../.test( $(this).find('input[name=email]').val() ) )
{
alert('Error!!!');
return false; //STOP PROPAGATION
}
//Its okay!
//send form!
$(this).parents('form').submit();
//click event stop propagation
return false;
});
});
HTML:
Submit
OR
<input type="submit" value="Submit" class="validate" />
OR
<button class="validate" >Submit</button>
In a quick look, I would say you are having a conflict of functions here. When you design a Submit Type, you are telling the browser that that will submit your form (on its action), on the other hand, that is inside a link that is calling a JS function. If you're manufacturing the submit in your JS, try to consider not use a Submit Type and see if it works more properly.
You might also try to replace the link for a simple "onSubmit" inside the form's Tag and call the JS function from there. This way, when the browser identifies that the user hit the submit button, he'll call a JS Function as you wish and if this function returns true, the submit will be allowed by the browser.

browser back button is not updating page

I'm setting the URL after the hashmark with a jquery click event. The URL is getting set properly but when I use the browsers back button it doesn't take me to the previous page.
Before my click event the URL looks like this:
http://example.com/menu.php?home
My click event looks like this:
$('#visits').click(function() {
$('#main').load("visits.php?type=1&view=1", function () {
location.href = "#visits";
});
return false;
});
My URL now looks like this:
http://example.com/menu.php?home#visits
It seems as though menu.php doesn't get called with the browsers back button.
Any idea what I'm missing?
You could code something like this:
var _hash = '';
function myHashChangeCallback(hash) {
// handle hash change
// load some page using ajax, etc
}
function hashCheck() {
var hash = window.location.hash;
if (hash != _hash) {
_hash = hash;
myHashChangeCallback(hash);
}
}
setInterval(hashCheck, 100);
Use the onhashchange event of the window, to check if the hash changes. This is getting called when you hit the back Button of your browser.
$(window).bind('hashchange',function() {
if (location.hash != '#visits') {
//Code to revert the changes on the page
}
}
Older versions of IE don't support hashchange, so you have to cheat by using setInterval to poll a few times a second and check if it's changed.
if($.browser.msie && $.browser.version < 7){
setInterval(function(){
if(window.location.hash != window.lastHash){
hashChangeHandler();
window.lastHash = window.location.hash;
}
}, 100);
}
else{
$(window).bind('hashchange',function() {
if (location.hash != '#visits') {
hashChangeHandler();
}
}
}

Categories