Javascript - concatenate field value to onclick button link? - javascript

I have an issue I need to fix on an existing app that I didn't initially write. Here is a snippet of code that doesn't do what it is intended to do. What it is supposed to do is take the value of the field and upon clicking "Search", append that to the redirection to pass in the querystring to the destination page:
<form name="frm_someform">
<input type="text" name="f_date" id="f_date"/>
<input type="button" value="Search" onclick="parent.location='runreport.asp?date=' + document.frm_someform.elements['f_date'].value); + '"/>
</form>
Now, as you javascript folks can plainly see, the concatenation doesn't work. I've searched high and low for how to properly concatenate, but something isn't translating correctly (in my head). Note that if I take out the concatenation, the redirection works fine, so there is something with that causing the issue. Yes, of course in the example above, I could simply make the form submit the proper value with a real 'submit' button, but I have whittled the code down here for simplicity - it is much more complex than the example I have above.
(*Note, I successfully tested concatenation through other javascript functions, but the possibility exists that the purely inline code must be different)
Thanks in advance,
Beems

Please, try this:
<form name="frm_someform">
<input type="text" name="f_date" id="f_date"/>
<input type="button" value="Search" onclick="parent.location='runreport.asp?date='+ document.getElementById('f_date').value"/>
</form>

Related

Form TextArea Losing Linebreaks

I am trying to repair an existing web form that submits a text area's contents to an external site's shopping cart service. The textarea is named "adtext" and upon submission it runs a few different scripts to calculate pricing, etc. It ultimately re-writes the ad content into a value named op31 (which is recognized by the shopping cart). The cart system recently got updated and it broke our script to convert line breaks in this text area into something that would be retained in that other site. I've tried looking at other sites, but it's over my head. I'm not particularly good at this stuff. I'm sure this isn't, and likely wasn't the best way to do it. I've seen CSS suggestions but don't understand it enough to actually implement them.
I've stripped out as much code as I comfortably could to clean it up, but still retain the issue. I'm wondering if someone could assist me with updating this function into something that would convert the "adtext" textarea's line breaks into something usable when written to "op31".
<script language="JavaScript" type="text/JavaScript">
function ConvertCarriageReturns(textarea, strReplace){
document.form.op31.value = escape(textarea.value)
for(i=0;i<document.form.op31.value.length;i++){
if(document.form.op31.value.indexOf("%0D%0A") > -1 ){
document.form.op31.value = document.form.op31.value.replace("%0D%0A",strReplace)
}
}
document.form.op31.value = unescape(document.form.op31.value)}
</script>
<form
action="https://(cart's url)/addtocart.aspx"
method="post"
name="form">
<textarea name="adtext" rows="12"></textarea>
<input alt="Add To Cart" name="add"
onclick="ConvertCarriageReturns(this.form.adtext,'<br>');
return checkwords(this)" src="https://....Add-To-Cart.gif"
type="image" />
<input name="item" type="hidden" value="(misc cart parameters" />
<input name="op31" readonly="readonly" type="hidden" />
</form>
You can use this native PHP function called nl2br
Like this:
$text = nl2br(this.form.adtext);

Making jquery function to work across multiple forms. (Making Jquery DRY)

I've created a simple js function called from a button-onclick to do something straight forward, submit the data 'selected' and open a new tab. This was a single use case, worked fine for this one case. But NOW, as I'm scripting out more and more widgets within my feature, (tabs presenting different tools, within the same DOM). I'm finding way harder to keep the DRY.
I want to set up the forms to have same general inputs, get which form it is by the form id, serialize and let the controller deal with the rest. Knowing the form id will allow some exceptions to some forms, if needed. Each attempt has me banging my head on my desk.
Why are no forms being executed?
And if I get one form working, why isn't the other? [Similar code sample with '.change']
How do I get this ideal code to work across all the forms
OldCode:
JS
function doaction(){
alert("I work perfectly");
}
HTML
<form id='form_w'>
<input type='hidden' name="action" />
<input type='text' name="term"></input>
<input type='button' onclick="doaction()"/>
</form>
Ideal Code:
jQuery
//$('form.results').submit(function(e){ //DIDNT WORK
$('.rbutton').click(function(e){ // NOT WORKING EITHER
alert("This alert doesnt exist");
var form_id = e.target.id;
// gather data
// submit data via ajax
// update the dom by adding another tab/widget.
});
HTML
<form id='form_tab_id1' class="results">
<input type='hidden' name="A_action" />
<input type='text' name="term"></input>
<input type='button' class='rbutton'/>
</form>
<form id='form_tab_id2' class="results">
<input type='hidden' name="A_action" />
<input type='text' name="term"></input>
<input type='button' class='rbutton'/>
</form>
<form id='form_tab_id3' class="results">
<input type='hidden' name="B_action" />
<input type='text' name="term"></input>
<input type='button' class='rbutton'/>
</form>
Essentially, a user posted a solution. I am greatful he did. It pointed me in the right direction. [It was removed for whatever Reason that may be. But thanks George.]
His Solution was the following.
JQuery
$('.rbutton').click(function(){
var form = $(this).closest('form');
}
After juggling with so many variations, my code was drifting into an unstable code set. I honestly didn't know how to go about this; JQuery is prolly my sworn enemy. But knowing that the code George posted should be working, and wasn't, it kind of pointed me into other factors that I didn't consider. [I didn't take into consideration the code was being executed before the tabs with the '.rbutton' element were being populated.]
The Solution that helped me make this a more DRY principle was the following JQuery;
JQuery
$(document).on('click','.rbutton',function(){
var form = $(this).closest('form');
// Actions that are needed to be performed
}
Reason why this helps, or at least with my code, it binds this function to any element with the class '.rbutton' including new instances. As i mentioned above,these buttons were created after the jQuery was being executed; So nothing was being binded essentially. The following will do the binding to newly created elements, as if tho there was an active listener doing the additional binding over the document even after the code had been executed.

Angularjs Form/Field validation using JavaScript function without directives

Is there a way to validate a field in angular without using a directive?
For example: I want to make following validation on an input field.
If field is empty we should show "Field must contain a value" message.
if field contains alpha Numeric characters we should show "Field can contain only digits".
An EVEN number - message to the user "Value must be an even number".
I want to make following validation in a call to JavaScript function.
I googled around and saw that there is a way to use ng-valid and $error , however I was not managed to make it work.
Code below is according to one of the answers I got:
<div ng-app>
<form name='theForm' novalidate>
<input type='text' name='theText' ng-model='theText' ng-pattern='/^[0-9]+$/'/>
<span ng-show='theForm.theText.$error.pattern'>Field can contain only digits</span>
<span ng-show='theText.length<1'>Field must contain a value</span>
<span ng-show='theText%2!=0&&document.getElementsByName("theText").value!=""&&!theForm.theText.$error.pattern&&!theForm.theText.$pristine'>Value must be an even number</span>
<br/><input type='submit' value='Submit' />
</form>
I want to take what inside the last [span] and put inside a JavaScript function in order to make it more generic and eventually change only JS and not the HTML when conditions are changing
Can someone please advise? a working example would be great.
I'm surprised no one has mentioned ui-validate
$scope.isOdd = function($value){
return $value % 2;
}
...
<form name="myform">
<input ng-model="myVal" name="value" required
ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input>
<pre>{{myform.value.$error|json}}</pre>
</form>
Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)
Here's a working demo
Take a look at the angularjs form documentation - http://docs.angularjs.org/guide/forms . In general, it is based on the HTML5 attributes like required, min, max, etc.
To get, for example, your first requirement done - "an empty field should show "Field must contain a value" message, yo uwould do something like that:
<input type="text" ng-model="user.name" name="uName" required /><br />
<div ng-show="form.uName.$invalid">
<span ng-show="form.uName.$error.required">Field must contain a value.</span>
</div>
For digits only field you can use the pattern attribute with a matching regular expression (example: http://www.wufoo.com/html5/attributes/10-pattern.html).
For even number validation, I'm not sure - I think you'd have to go with custom validation for that (meaning you'd have to create a directive) or use the pattern attribute somehow.
Last but not least - remember to add novalidate to the <form> tag. Otherwise the browser will try to validate your fields as well and you don't want that:
<form ... novalidate>
...
</form>
I know the question is old and I know you didn't want a directive but you may consider using a directive if it's "Angular" way... Well here is my Angular-Validation. I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... It is so crazy simple, you need 2 lines 1 line of code, 1 line for the input, 1 line for error display, that's it... never more and never less!!! Enough said, let's give some examples:
<!-- example 1 -->
<label for="input1">Email</label>
<input type="text" validation="email|min_len:3|max_len:25|required" ng-model="form1.input1" name="input1" />
<!-- example 2 -->
<label for="input2">Alphanumeric + Exact(3) + required</label>
<input type="text" validation="alpha|exact_len:3|required" ng-model="form1.input2" name="input2" />
So I can define whatever amount of validation rules (already 25+ type of validators) which I want in a simple directive validation="min_len:2|max_len:10|required|integer" and the error message will always display in the next <span> Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add. Another bonus, I also support whichever trigger event you want, most common are probably onblur and onkeyup. Oh and I also support multiple localization languages via JSON external files. I really added all the imaginable features I wanted into 1 crazy simple directive.
No more clustered Form with 10 lines of code for 1 input (sorry but always found that a little extreme) when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And no worries about the form not becoming invalid, I took care of that as well, it's all handled the good "Angular" way.
Take a look at my Github project Angular-Validation... I'm sure you'll love it =)
UPDATE
Another candy bonus! To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000" to make a 5 sec. timeout. Full example:
<input type="text" ng-model="form1.input1" typing-limit="5000" validation="integer|required" name="input1" />
<span class="validation text-danger"></span>
UPDATE #2
Also added input match confirmation validation (ex.: password confirmation), here is a sample code
<!-- input match confirmation, as for example: password confirmation -->
<label for="input4">Password</label>
<input type="password" name="input4" ng-model="form1.input4" validation="alpha|min_len:4|required" />
<label for="input4c">Password Confirmation</label>
<input type="password" name="input4c" ng-model="form1.input4c" validation="match:form1.input4,Password|required" />
UPDATE #3
Refactored the directive so that the requirement of having a <span> to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.
DEMO
Added a live demo on Plunker
Well you can try to create a func
<span ng-show='isEven(theText)'>Value must be an even number</span>
$scope.isEven=function(data) {
if(data) {
return data%2===0
}
return true;
}
The method can either be defined on the current controller scope or on $rootScope.
Not a very angular way, as directives would be better but i think it would work.

Javascript Form Input Retrieval

Why is it that in a form that contains a Text Box and a Submit Button, I can Alert what has been typed in the text box by the user, but can't print it on the page? What am I doing wrong?
Here's the code
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="submit" value="Join" onClick="serb(this.form)" />
<script type="text/javascript">
function serb(form){
var x = document.Serb.Name.value;
alert(x); \\this alerts
document.write(x); \\this should print on page
}
</script>
For some reason, the alert works fine and displays exactly what the user typed in the username box after pressing 'Join'. However, it won't print the information on the page. Why is that?
It does work. The value in the textbox is printed on the page.
BUT:
\\ do not mean anything in Javascript. Comments begin with //. This is most likely the reason why you are not seeing the value being written
document.write replaces whatever is in the HTML page with its argument. (If it is called after the document is loaded). So unless you are trying to learn Javascript this is not a very good idea.
Actually it is not a very good idea to use it even when learning Javascript, unless you are trying to learn how document.write works.
There are flexible (and better) ways to manipulate the content of a page, starting from the humble getElementById to complex DOM manipulation
It is not a good idea to use document.write() after the page has been loaded/parsed. At that point, it will overwrite the page HTML with new content. document.write() is generally used while the page is being loaded to insert content at a particular point into the page as it's being loaded.
If you want to put the value into some item on the page, then you need to use appropriate DOM methods for that, putting the value into an input field, setting the innerHTML on a div, etc...
You can read about document.write here: https://developer.mozilla.org/en/document.write.
Here's an example of fetching the value from the field and putting it in another object on the page without using document.write(): http://jsfiddle.net/jfriend00/dU8Sr/.
HTML:
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="button" value="Join" onClick="serb(this.form)" />
</form>
<br>
<br>Output: <span id="output"></span>
Javascript:
function serb(form) {
var x = document.Serb.Name.value;
document.getElementById("output").innerHTML = x;
}

Form not submitting with JS

I have the worlds most simple javascript function:
fnSubmit()
{
window.print();
document.formname.submit();
}
Which is called by:
<button type="button" id="submit" onclick="fnSubmit()">Submit</button>
All is well and good, the print dialog shows up, however after printing or canceling the print I get the following error:
"document.formname.submit is not a function"
My form is defined as follows: (obviously I am not using formname in the actual code but you get the idea)
<form name="formname" id="formname" method="post" action="<?=$_SERVER['SCRIPT_NAME']?>">
Obviously I am not trying to do anything special here and I have used similar approaches in the past, what in the world am I missing here?
In short: change the id of your submit button to something different than "submit". Also, don't set the name to this value either.
Now, some deeper insight. The general case is that document.formname.submit is a method that, when called, will submit the form. However, in your example, document.formname.submit is not a method anymore, but the DOM node representing the button.
This happens because elements of a form are available as attributes of its DOM node, via their name and id attributes. This wording is a bit confusing, so here comes an example:
<form name="example" id="example" action="/">
<input type="text" name="exampleField" />
<button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button>
</form>
On this example, document.forms.example.exampleField is a DOM node representing the field with name "exampleField". You can use JS to access its properties such as its value: document.forms.example.exampleField.value.
However, on this example there is an element of the form called "submit", and this is the submit button, which can be accessed with document.forms.example.submit. This overwrites the previous value, which was the function that allows you to submit the form.
EDIT:
If renaming the field isn't good for you, there is another solution. Shortly before writing this, I left the question on the site and got a response in the form of a neat JavaScript hack:
function hack() {
var form = document.createElement("form");
var myForm = document.example;
form.submit.apply(myForm);
}
See How to reliably submit an HTML form with JavaScript? for complete details
Given that your form has both an id and a name defined, you could use either one of these:
With the form tag's id:
document.getElementById('formname').submit();
With the form tag's name attribute:
document.forms['formname'].submit();
Try this:
fnSubmit()
{
window.print();
document.getElementById("formname").submit();
}
The most likely culprit is IE confusing JavaScript variables, ids, and names. Search in your source for something sharing the name of your form.
Place a input button inside your form.
Give tabindex="-1" on it.
Make It invisible using style="display:none;".
Like This
<input type="submit" tabindex="-1" style="display:none;" />

Categories