I have an order submitting form where I want to replace URL texts with corresponding HTML links. I've found the following code on Stackoverflow:
get_url = function() {
var urls = document.getElementById('w_descr').firstChild;
urls.nodeValue = replaceURLWithHTMLLinks(urls.nodeValue);
}
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
I'm calling the get_url() function on click even of the form submitting button. It works fine. However the submitted orders have a feature of editing. If you edit an order and click on the Submit button again, the function will work again and will duplicate the existing link.
Could anybody help me to figure out how can I prevent that to happen? I mean - how to modify the script above to not to duplicate the links which are already in HTML form.
Thanks in advance.
Always store the text 'plain' (without the links), and only add the links when outputting the text for display.
When outputting the text for editing, output the 'plain' text.
Related
I'm working on a jsp containing some checkboxes. My jsp is linked to a form (called SuiviTransfertForm), and this form has an attribute called checkboxUID, which is an array containing the ids of my checked checkboxes.
private String[] checkboxUID = {};
This attribute is mapped with the checkboxes of my jsp like this :
<html-el:multibox name="suiviTransfertForm" property="checkboxUID"/>
I would like to follow a link on this jsp and get the content of checkboxUID when I'm on the next page.
On the next page, I'm getting back my form like this :
SuiviTransfertForm suiviTransfertForm = (SuiviTransfertForm) form;
The problem is that checkboxUID is correctly filled if I stay on the same page, but always empty when I'm changing page. I can't find a way to achieve this.
Many thanks for your help !
When you're clicking the link it's not submit the form. Hence you cannot get any values from form. Try sending through URL (script way - though it's not a best practice)
var arrayValues = [12,34,54,67]; //Get the selected checkbox values when clicking link
var QueryString = JSON.stringify(arrayValues);
var a = document.getElementById('yourlinkId');
a.href = 'myLink?params='+QueryString;
or you can use jQuery for simple code,
$('#yourlinkId').attr({"href" : '/myLink?params=' + arrayValues.join(',')});
Try and let me know if it helps.
I finnaly fixed the problem by listing my checked checkboxes and setting them to the form after clicking my link.
Many thanks for your help guys !
i am using bootstrap tags input in my site.
basically what i am trying to do is,
ask user to type urls into a text field, now if the text is valid url then only convert it into tag otherwise don't.
is there any way to process text before converting into tags?
any help would be appriciated.
Thanks
Bootstrap tags have beforeItemAdd event which triggered just before an item gets added. Bootstrap tags
$('input').on('beforeItemAdd', function(event) {
/* Validate url */
if (/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(event.item)) {
event.cancel = false;
} else {
event.cancel = true;
}
});
Bootstrap Tags Input have a hidden input before convert to tags you find it by following code:
$(".bootstrap-tagsinput input[type="text"]").keyup(function(){
// do your validation
});
you can see it by get an inspect element in your page. it will convert to tags after you press enter button you can do your validation until it's on hidden input.
It will be there:
<div class="bootstrap-tagsinput">
<span class="tag label label-info">Test<span data-role="remove"></span></span>
<input type="text" style="width: 7em;" size="1"> // here is!
</div>
If your input id is "tag-input", all you have to do is use a beforeItemAddcallback provided by the library itself like so:
$('#tag-input').on('beforeItemAdd', function(event) {
var tag = event.item;
if(true){ //if tag is not a url or process other text conditions.
event.cancel = true
}
});
If you don't set event.cancel to false, the add will go through.
You can check the documentation on this method here.
Also , as it is clear in this case that documentation does not say how to cancel the event. In such cases its simple enough to just check the code itself. I this case this code in the plugins github repo makes it plenty clear how to use this option.
I have a form with a « newInput » button, which add dynamically in javascript a new input when I click to it.
When I have an error in my form, I re-load the view with the form. It’s normal, but .. Because I use dynamic javascript for adding new input, all the input added are removed when I reload..
There is something I can do ?
This is an exemple of my view.tpl :
<input
type="text"
placeholder="ex: cerise"
onfocus="javascript:autoComplet('jigd1', '{site_url('recettes/getIngredient')}')"
value="{set_value('igd[]')}" id="jigd1" name="igd[]"
/>
{form_error('igd[]')}
I add a partiel code of my js file
var cpt=1;
function addField(uriIngredient, uriLabel) {
try
{
cpt=cpt+1;
var inputIgd = document.createElement('input'),
button = document.createElement('input'),
div = document.createElement('div'),
inputIgd.setAttribute('type','text');
inputIgd.setAttribute('name','igd[]');
inputIgd.setAttribute('id','jigd'+cpt);
button.setAttribute('type','button');
button.setAttribute('onclick','javascript:supField("igd'+cpt+'")');
button.setAttribute('value','Supprimer');
div.setAttribute('id','igd'+cpt);
div.appendChild(inputIgd);
div.appendChild(button);
document.getElementById("listIgd").appendChild(div);
...
After some research, I tried to look at what someone said me, that's say localStorage, and it is very nice. But I used an exemple for only one input because i wrote it in my html, but I don't know how to do for recreate all inputs .. And particularly because I use javascript to add new inputs, I don't know if I can recreate all inputs .
check the form before submitting, that way you won't have to reload the page, for example using jquery ...
$("#myformid").on("submit", function(){
var goodtogo = true;
// some code here to check the form, if there's an error --> goodtogo = false;
if (!goodtogo) return false; // and some other code to display the errors
});
That way, if there's an error , the form won't submit and won't reload.
If you have to check something in a database (for example) like checking if a username already exists, you'll have to use ajax.
i have a text area and a click me. In that text area, if a user enters some URLs then the input should be marked invalid on the button click.
For example, if my input is
"StackOverFlow, the greatest codding buddy you could ever have. The URL: www.stackoverflow.com You can also checkout meta.stackoverflow.com which is also super cool"
At button Click the error should be.
"Form submit failed, because you have entered some URLS. The URLs are
- www.stackoverflow.com
- meta.stackoverflow.com"
I would like a pure javascript solution. No jquery please.
Took one of those regex from the link below:
http://regexlib.com/Search.aspx?k=URL
Then :
var input = document.getElementbyId(id_of_your_form);
var x = input.match(/reg_ex_here/g);
if (x.length>0) { // x[i] will hold the url
var urls=x.concat();
alert(urls);
}
It's not properly tested ... but hope you get the idea..
I have some javascript which catches changes to a form then calls the form's regular submit function. The form is a GET form (for a search) and i have lots of empty attributes come through in the params. What i'd like to do is to delete any empty attributes before submitting, to get a cleaner url: for example, if someone changes the 'subject' select to 'english' i want their search url to be
http://localhost:3000/quizzes?subject=English
rather than
http://localhost:3000/quizzes?term=&subject=English&topic=&age_group_id=&difficulty_id=&made_by=&order=&style=
as it is at the moment. This is just purely for the purpose of having a cleaner and more meaningful url to link to and for people's bookmarks etc. So, what i need is something along these lines, but this isn't right as i'm not editing the actual form but a js object made from the form's params:
quizSearchForm = jQuery("#searchForm");
formParams = quizSearchForm.serializeArray();
//remove any empty fields from the form params before submitting, for a cleaner url
//this won't work as we're not changing the form, just an object made from it.
for (i in formParams) {
if (formParams[i] === null || formParams[i] === "") {
delete formParams[i];
}
}
//submit the form
I think i'm close with this, but i'm missing the step of how to edit the actual form's attributes rather than make another object and edit that.
grateful for any advice - max
EDIT - SOLVED - thanks to the many people who posted about this. Here's what i have, which seems to work perfectly.
function submitSearchForm(){
quizSearchForm = jQuery("#searchForm");
//disable empty fields so they don't clutter up the url
quizSearchForm.find(':input[value=""]').attr('disabled', true);
quizSearchForm.submit();
}
The inputs with attribute disabled set to true won't be submitted with the form. So in one jQuery line:
$(':input[value=""]').attr('disabled', true);
$('form#searchForm').submit(function() {
$(':input', this).each(function() {
this.disabled = !($(this).val());
});
});
You can't do it that way if you call the form's submit method; that will submit the entire form, not the array you've had jQuery create for you.
What you can do is disable the form fields that are empty prior to submitting the form; disabled fields are omitted from form submission. So walk through the form's elements and for each one that's empty, disable it, and then call the submit method on the form. (If its target is another window, you'll then want to go back and re-enable the fields. If its target is the current window, it doesn't matter, the page will be replaced anyway.)
Well one thing you could do would be to disable the empty inputs before calling "serializeArray"
$('#searchForm').find('input, textarea, select').each(function(_, inp) {
if ($(inp).val() === '' || $(inp).val() === null)
inp.disabled = true;
}
});
The "serializeArray()" routine will not include those in its results. Now, you may need to go back and re-enable those if the form post is not going to result in a completely refreshed page.
Maybe some of the proposed solutions worked at the moment the question was made (March 2010) but today, August 2014, the solution of disabling empty inputs is just not working. The disabled fields are sended too in my Google Chrome. However, I tried removing the "name" attribute and it worked fine!
$('form').submit(function(){
$(this).find('input[name], select[name]').each(function(){
if (!$(this).val()){
$(this).removeAttr('name');
}
});
});
Update:
Ok, probably the reason because disabling fields doesn't worked to me is not that something changed since 2010. But still not working in my Google Chrome. I don't know, maybe is just in the linux version. Anyway, I think that removing the name attr is better since, despite what policy takes the browser about disabled fields, there is no way to send the parameters if the name attr is missing. Another advantage is that usually disabling fields implies some style changes, and is not nice to see a style change in the form a second before the form is finally submited.
There is also a drawback, as Max Williams mentioned in the comments, since the remove name attr solution is not toggleable. Here is a way to avoid this problem:
$('form').submit(function(){
$(this).find('input[name], select[name]').each(function(){
if (!$(this).val()){
$(this).data('name', $(this).attr('name'));
$(this).removeAttr('name');
}
});
});
function recoverNames(){
$(this).find('input[name], select[name]').each(function(){
if ($(this).data('name')){
$(this).attr('name', $(this).data('name'));
}
});
}
However, I think this is not a very common case since we are submitting the form so it is assumed that there is no need to recover the missing name attrs.
Your problem helped me figure out my situation, which is a bit different - so maybe someone else can benefit from it. Instead of directly submitting a form, I needed to prevent empty form elements from being collected into a serialized array which is then posted via AJAX.
In my case, I simply needed to loop through the form elements and disable all that were empty, and then collect the leftovers into an array like so:
// Loop through empty fields and disable them to prevent inclusion in array
$('#OptionB input, select').each(function(){
if($(this).val()==''){
$(this).attr('disabled', true);
}
});
// Collect active fields into array to submit
var updateData = $('#OptionB input, select').serializeArray();
Or serialize, clear empty key=value pairs with regex and call window.location:
$("#form").submit( function(e){
e.preventDefault();
//convert form to query string, i.e. a=1&b=&c=, then cleanup with regex
var q = $(this).serialize().replace(/&?[\w\-\d_]+=&|&?[\w\-\d_]+=$/gi,""),
url = this.getAttribute('action')+ (q.length > 0 ? "?"+q : "");
window.location.href = url;
});
Another approach I always recommend is to do that on server side, so you are able to:
Validate the input data correctly
Set default values
Change input values if needed
Have a clean URL or a friendly URL such as "/quizzes/english/level-1/"
Otherwise you will have to deal with text input, select, radio etc...