Merging search terms from 2 separate input fields - javascript

So I have javascript code to prepend "tag:" or "vendor:" before every search term, but I wanted to hide that from the user, so I created a hidden input field to send the code but it's not properly prepending the "tag:" and "vendor:" before every word. and instead inputs the entire string, then the search terms.
<form method="get" action="/search" id="search-home">
<button type="submit" value="search"></button>
<input type="hidden" name="type" value="product" />
<input type="hidden" name="q" class="searchtext" />
<input type="text" name="red" placeholder="Search"/>
</form>
<script>
$(document).on('submit','#search-home',function(){
var searchtext = $('.searchtext').val();
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
</script>
Here's what the Url looks like with the code
http://zzz.co/search?type=product&q=tag%3A+OR+vendor%3A&red=tote#fullscreen=true&search=home
Here's what it's supposed to look like.
http://zzz.co/search?type=product&q=tag%3Atote+OR+vendor%3Atote#fullscreen=true&search=home

You're getting an empty value and inserting it here:
$(document).on('submit','#search-home',function(){
var searchtext = $('.searchtext').val(); // <- HERE
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
What you should be doing is getting the user given query, which is the input you named "red".
$(document).on('submit','#search-home',function(){
var searchtext = $('input[name="red"]').val();
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
With the above fix, your URL will look similar to:
http://zzz.co/search?type=product&q=q=tag%3Atote+OR+vendor%3Atote&red=tote.
I do not know where you're getting your hashbang(#) from, but I would assume it will append at the end as before.
If you want to get rid of the red=tote part, you have a few options. Emptying the value via $('input[name="red"]').val(''); will make it appear in your url as red=. If you want it gone entirely, you should use $('input[name="red"].remove();.
I would also advise having your "on" hook attached to the form, not the entire document. This is just a good practice to avoid using unnecessary resources as this hook will bubble every time a form is submitted, regardless of the selector. Instead, consider:
$('form#search-home').on('submit', 'button[type="submit"]', function() { ... };
That way it will only bubble when a submit event happens on that specific form, greatly reducing the possible instances those resources are used.

Related

How to Completely Prevent Web Form Input Text Item change

I have this simple web-form
<form id="MyFormDiv" method="post">
<input type="number" name="cmp_no" id="id_cmp_no">
<input type="text" name="cmp_lname" maxlength="40 id="id_cmp_lname">
<input type="submit" name="submit" value="Save" id="submit-id-submit">
</form>
and this form will be used for both add and update.
When insert I have no problem, but when update I don't want to allow user to update or change the value of item which its id= "id_cmp_no"
I used javascript code to set its readonly property to true but that was not the 100% solution, because user can use browser inspect tool and see page source and change it's value before submitting the form, and therefore the readonly property is not useful.
Can I override it's onchange event to prevent change of it's value even if the value changed from page source using inspect tool.
Any one can help, thank you in advance
There is nothing that stops a user from changing values in browser, u can try solutions given in the above answers but be cautious user can dig out number of ways to do so like by using firebug/inspect element/ what ever..
What we can do is checking our values on server side and prompting user if they mismatch.
Shouting again ..
Never trust/depend on client....
If a user is skilled enough to open dev tools and change values from there, chances are they can also alter any JS code that prevents editing the readonly value.
So, there is no substitute to proper server-side validation.
You could check that the value is not being altered from the form's onsubmit event handler (see below), but keeping in mind what I and many commenters stated above.
$("form").on("submit", function(e) {
//check value of the input
if(this.someInput.value != 1) {
//do something here
//return false; if you want to block submit
}
return true;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="number" name="someInput" readonly value="1"/>
<button type="submit">Submit</button>
</form>

Angular: how to reset form elements that map to different data

My angular app has > 1 forms on a page. Each form can be saved or reset. The fields on each form don't necessarily map to its own data object.
For example I have two pieces of data that must be gotten and saved separately. Let's call the json chunks, a and b.
HTML:
<form>
<input type="text" ng-model="a.foo"/>
<input type="text" ng-model="b.bar"/>
</form
<form>
<input type="text" ng-model="b.bar[0].baz"/>
<input type="text" ng-model="a.boo"/>
</form
If the first form were mapped to just a and the second to b it would be a simple matter of resetting the data. But I don't want to reset all the a or b data for all forms on the page. I just want to reset the specific data fields for the inputs represented on a particular form.
My current logic mostly works. On cancel I get the elements in the form, get their ng-model attributes and dynamically reset properties on a and b depending on the ng-model string value. This seems "dirty" and plus it doesn't work for some ng-model attributes which use the $index special variable because the attr value isn't parsed by angular when doing .attr(). What's the best solution for this? Different models for each form that map back to the original data?
Make a deep copy of the object you are editing when opening the form and edit it ( angular.extend)
when save just use your save logic
on cancel you will need to do nothing
e g
.controller('myctrl', function($scope, dataService) {
$scope.data = angular.extend( {}, dataService.get())
$scope.save = function ( ) {
dataService.set($scope.data)
}
})
I haven't done this before, but you can try having something like below:
<form>
<input type="text" ng-model="form1.element1" ng-change="a.foo=form1.element1"/>
<input type="text" ng-model="form1.element2" ng-change="b.bar=form1.element2"/>
</form>
<form>
<input type="text" ng-model="form2.element1" ng-change="b.bar[0].baz=form2.element1"/>
<input type="text" ng-model="form2.element2" ng-change="a.boo=form2.element2"/>
</form>
to have an easy reference to your form-specific elements. And then for resetting, you can simply reset the form1 or form2 objects with initial values using angular.copy().
One thing you may need to watch with this approach is, once you enter some values and reset although on the form1 or form2 will be reset, there may still be values in a and b objects, you might want to handle that (disable submit for e.g.)

How to store value entered in an input textfield in a database

I am using springsourcetoolsuite, grails project and I am coming across this problem of storing the value entered in the textfield into a table in the database created in mysql and connected to grails. Now I have a domain class called property having variables address, city,
zipcode, country etc. which are also fields of the table property in mysql database.
When I ask user to fill in using this piece of code-(gsp views)
<body>
<g:textField name="address" maxlength="40" value="${propertyInstance?.address}" />
</body>
it works and the value is stored in database.
However I am required to append an input field on each button click, so i have put this input field in a function called add(). Here is the code-
<head>
<script type="text/javascript">
function add() {
var newP = document.createElement("p");
var input1,
area = document.getElementsByTagName("form")[0];
input1 = document.createElement("input");
input1.type = "g:textField";
input1.placeholder = "street";
input1.value = "${propertyInstance?.address}";
newP.appendChild(input1);
area.appendChild(newP);
}
</script>
</head>
<body>
<g:form name='prop' method="post" action="save">
<input type="button" value="+Add" onclick= "add();" ><br>
<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</g:form>
</body>
Now when i do this and run it, it takes null value and prints an error saying 'address cannot be null'. Now i cannot see what is wrong, but if anyone is familiar with groovy/javscript.. please help me figure out whats wrong.
Thanks a lot.
I'm guessing you did not use the scaffolding feature to generate your views in first place. If you didn't, it's a good way to start understanding the basics of grails. In your case specifically, you need to put your fields that you want to pass to the controller (like address) inside the form tag. Like:
<body>
<g:form name='prop' method="post" action="save">
<g:textField name="address" maxlength="40" value="${propertyInstance?.address}" />
<input type="button" value="+Add" onclick= "add();" ><br>
<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</g:form>
</body>
Another thing is you can't create a tag input and put its type as "g:textfield". The html input fields only have limited types. The one you want to use in this case is really "text". In any case, the grails' tags are rendered before the javascript (in the server-side) while javascript code is rendered client-side. So the first time the page is rendered they will work. But to insert something dynamically in your page, you need ajax because the grails' tags are already rendered. The value ${propertyInstance?.address} needs to be processed at the server, returned and established in your field. Therefore you need to make an async request. Anyway JQuery is your guy.
Also, for what you're doing, JQuery helps to manipulate HTML DOM, that will make your work so much easier.

Passing forms between html pages

I've got an assignment to pass data between 2 .htm pages, in a manner which the source gets copied to the destination.
sourcePage.htm contains a form. (it contains more controls this is just a sample)
<form id="myform" action="destPage.htm" method="get" >
<input type="text" name="user" />
<input type="submit" name="submit" value="Submit" />
</form>
and destPage.htm is blank.
Using JavaScript I am required to parse the data from the url, that part isn't the problem
, the problem is that I am also required that destPage would be an exact duplicate of sourcePage.
My question is, if there's a way to pass the form as an object or some way to pass the control types and their properties along side the data.
You specified in the answer of ek_ny, that you want to dynamically build the form, based on it's input.
You can do this, in fact, with the JavaScript DOM:
var i = document.createElement('input');
i.setAttribute('type', "text");
i.setAttribute('name', "user");
var f = document.createElement('form');
f.setAttribute('action', "destpage.html");
// etc.
f.appendChild(i);
document.getElementById('container').appendChild(f);
The form will be added as a child in the <div id="container"> container.
Now you can use hidden input elements, which give, for instance, the specifics of the form:
<form>
<input type="hidden" name="x_type" value="input-text" />
<input name="x" type="text" />
<input type="hidden" name="y_type" value="select:[...]" />
<select name="y">
...
</select>
</form>
As far as I know, you won't be able to do a post between two pages. At least when I've attempted that you get an error-- it really doesn't make sense to have a post from one static page to the other (right?). What you can do is serialize the data you want to pass, put it on the url string to the next page and then deserialize that data and populate the controls on the destination page. If the html between the two pages is identical, then it should be pretty straightforward, if not it will be a little tricker. If you used jQuery it would be pretty easy, because you could serialize an entire form. If you need to come up with a generic solution (and you should, because it will help you learn) that's one thing, if you need to just get it working for this assignment and there are only a couple of form fields, you'll just need to encode the values you want to pass and pass them on a URL string with a get request.

jQuery Selecting the first child with a specific attribute

I have a form in HTML with multiple inputs of type submit:
<form id = "myForm1" action="doSomethingImportant/10" class="postLink" method="post">
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
<input type="submit" value="clickThisLink"></input>
<input type="submit" value="Don'tclickThisLink"></input>
</form>
What I want to do is select only the first input with type submit while ignoring the others, the snippet of code I currently have is as follows, note it is within a for-each loop that goes through all forms on my page, hence (this) to avoid confusion:
var name = $(this).find("input[type='submit']").val();
I'm thinking this already grabs the first input of type submit by default, I'm not sure if that assumption is correct or if there's a more formal way of going about it, thanks.
Try:
$(this).children("input[type='submit']:first").val();
how about the first selector
var name = $("input[type='submit']:first").val();

Categories