Modification JSON with input html in js - javascript

I'm learning JS and i'm trying to make a little app with node.js with JSON on.
I managed to get what I wanted in my json and put it in my html as input, with the json data as "value". When I click on the elements, we can change each of them, since they are inputs, and so I change their "value". Until then, everything works, but when I modify my 1st element of the list, all the elements are modified in the json...
And only the first element in my HTML changes my json, the others don't, they change but don't register in the json, and I have trouble understanding why.. I tried forEach and this.el but nothing works, it doesn't understand my data..
There is the code
var newValue = $("#snippetTitle").on("change paste keyup", function () {
    if (newValue.val() != $("#snippetTitle:input")) {
        for (var i = 0; i < jsonParse.snippets.length; i++) {
            newValueTitle = jsonParse.snippets[i].title = newValue.val();
            writeValue = JSON.stringify(jsonParse, newValueTitle);
            fs.writeFileSync('save/snippets.json', writeValue, 'utf8');
        }
    } else {
    }
});
Thank you for explaining to me how I could do so that each element could be modifiable, and especially that it is recorded in the json...
I'm not looking for complete solutions, just help to understand what to do.

Related

Django: populate the field based on previous field value - missing the last step to make it work

Like many, I want to populate a field in a django form based on what is selected in another field. I've read alot of answers with javascript(I struggle in javscript, so that's where I'm having trouble with the exemples), and I almost got it working, but the last step(updating the field itself) isn't working so I'd love some help with that part.
Here are the 2 fields. The first fieldthat gets populated from a query and is located in a div named #merch in the form
merchandise = forms.ModelChoiceField(label='Merchandise', queryset=Merchandise.objects.all(),
merch_price = forms.DecimalField(label='Price', min_value=0, max_value=800,
initial='0.00',decimal_places = 2, max_digits=10)
Upon selection, the second field(div named #price) should then display the price based on the merchandise selected. I created the view for the ajax request:
def check_item_price(request):
if request.method == "GET":
item = request.GET.get('item', '0')#the zero as default doesn't seem to work. To verify
price = Merchandise.objects.get(id = item)
return JsonResponse(price.item_price, safe=False)#is it safe to turn safe off?
and the url
url(r'^_item_price', views.check_item_price, name='_item_price' )
Calling the url manually works great, it returns the price in json format
And here is the javascript that is in the html form. The first part works, upon change it calls the url and a json object is returned, but the second part that should update the second field isn't working. I admit my lack of knowledge in javascript is probably at fault here. I tried many variations based on examples, none worked for me.
<script type="text/javascript">
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
$('#price').append("<option value=" + data.value + "></option>");
});
});
});
</script>
Any pointers on what to fix in the javascript?
Thanks!
After letting it marinate in my head for 2 months, I went back to it and finally made it work. Here is the right code
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
document.getElementById('id_merch_price').value=data;
});
});
});
</script>
First, the ID wasn't precise enough, but also the way of updating it wasn't the right one it seems. I truly feel lost anytime I have to do research on javascript or jquery. So may ways to do the same thing, it's almost impossible to learn for a casual coder like me.

How to get selected row data from Vaadin Grid with polymer?

I am trying to get the selected row data form vaadin grid using polymer. But I am not able to get.
Here is the my code:
this.mileageGrid = this.$$("#mileageSectionGrid");
this.mileageGrid.addEventListener('selected-items-changed', function() {
var selected = this.mileageGrid.selection.selected();
this.selectedRowData = this.mileageGrid.getSelectedRow();
this.selectedRowData = this.mileageGrid.selection.getSelectedRow();
if (selected.length == 1) {
detailsOpenIndex = selected[0];
this.callback(detailsOpenIndex);
//this.fire("change-mileage", this.mileage);
}
}.bind(this));
I didn't get any idea after searching from google and vaadin grid document also.
Can anybody tell me, how to get selected row data?
These two lines seem to be incorrect, and look more like something from the Vaadin Java framework API:
this.selectedRowData = this.mileageGrid.getSelectedRow();
this.selectedRowData = this.mileageGrid.selection.getSelectedRow();
I think those are probably causing errors in the browser and any following JavaScript is not working. Check for any errors in your browser’s console.
Otherwise I can’t spot any issues in your code (I’m just not sure if you’ve declared detailsOpenIndex and this.callback outside the visible code).

How do I get data entered from a user which gets parsed in JSON into a Javascript file that already loads another set of JSON data?

I'm trying to make a little flashcard game that allows someone to customize a set of flashcards by entering their own questions and answers through a <textarea> field via HTML. I am stuck on how I can get this data to link to a javascript file that actually runs the flashcard game. The javascript file that runs the game already ready has a default set of JSON data that is linked to that particular javascript file. How would I go about swapping these sets of JSON data so the user use the flashcards with the questions and answers they have created?
Here are some visuals and code to help you understand what is going on here:
The <textarea> shows where a user can enter their own questions and answers.
Then a user can click the button "Create flashcards" and the data that was in the tags gets parsed into JSON like this:
I have a file titled flashcards.js that already has a default set of flashcard data that is being loaded from a JSON file. Here is the code that does this:
var jsonUrl = "questionsAndAnswersItalian.json";
var cardIndex = 0;
var qs;
var numCards;
var maxIndex;
var isFlipped = 0;
var colorIndex = 0;
var colorClasses = ['c0','c1','c2','c3'];
(a bunch of code to make the game work in between)
function init() {
$.getJSON(jsonUrl, function(jsonObject) {
qs = jsonObject;
numCards = qs.length;
maxIndex = numCards-1;
displayCard();
});
}
function displayCard() {
$("#card").fadeOut(400,function(){
colorIndex = getRandomInteger(0,3);
$("#card").addClass(colorClasses[colorIndex])
isFlipped = 0;
var newHtml = "<h2>Question Words</h2>";
newHtml += qs[cardIndex]["q"];
document.getElementById("question").innerHTML = newHtml;
}).fadeIn(400);
}
That piece of code outputs something that looks like this:
To sum it up, what I'm basically asking is how do I take the JSON data that is created from clicking the button "Create flashcards" and make it load using my flashcards.js file, or if there is anyway to dynamically swap the user created JSON data with this variable :
var jsonUrl = "questionsAndAnswersItalian.json";
If you need any more information to help understand what is going on here, please don't hesitate to ask.
Any input, help or advice would be much appreciated!
Thanks!

jQuery.Data set's or get's wrong item

I am using something similair to this:
$("input").each(function(number,element)
{
var inputField=$(element);
if(inputField.data("FieldLocalizationStrings") == null)
inputField.data("FieldLocalizationStrings", []);
}
And to add data:
var data=inputField.data("FieldLocalizationStrings");
data.push({Language:inputField.attr("language"),Value:inputField.val()});
But when i try to retreive, it seems to ignore on which DOM element it has been saved and just loads it like it was all saved on the same element. Anyone an idea why this would happen? i have used the same technique before and it proved to work, but now i can't figure out why this is hapening.
I confirmed it does not save it to multiple input fields, but when loading it acts like it is.
Update
Added a fiddle here
$("input").each(function(number,element)
{
var inputField=$(element);
if(inputField.data("FieldLocalizationStrings") == null)
inputField.data("FieldLocalizationStrings", [
{
Language:inputField.attr("language"),
Value:inputField.val()
}
]);
//If later you want to append to the data
inputField.data("FieldLocalizationStrings").push({/* Your data */})
}
http://api.jquery.com/jQuery.each/ - as for documentation you'll get value as second parameter. If you want set data for an element you should use this.

Using jQuery to pull text from a specific <td>

I'm running an AJAX query on an external page, and am attempting to only return the data from the County . My current script is pulling the text from all of the table cells, but I cannot for the life of me get it to simply pull the county name.
The current script that is being run:
$( ".zipCode" ).each(function( intIndex ){
var zipCodeID = $(this).attr('id');
console.log('http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip='+zipCodeID);
$.ajax({
url: 'http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip='+zipCodeID,
type: 'GET',
success: function(res) {
var headline = $(res.responseText).find("p").text();
console.log(headline);
$('#'+zipCodeID).empty();
$('#'+zipCodeID).append(headline);
}
});
});
An example of the page that is being queried:
http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip=56159
This should work for all entered ZIPS. The page layout is the same, I just can't get the function to return only the county. Any help or advice would be awesome. Thanks!
With the complete lack of ids and classes on that page, you don't really have much to go on. If you have access to the source of that page, stick an id or class on the cell and make your life so much easier. If not, you'll have to use what you know about the structure of the pages to find the county. Something like this will work specifically on that one page you linked to. If other pages have slight variations this will fail:
var headline = $(res.responseText).find("table > tr:eq(2) > td:eq(3)").text();
This assumes that there is only ever one table on the page and that the county is always in the 3rd cell of the 2nd row.
You're basically screen scraping. I somehow think you'll have issues with this due to cross domain and other things, but that is ancillary to the question.
You need to walk through the resultant page. Assuming there is only ever one page on the screen, it'll look like something this:
var retVal = [];
// Basically, for each row in the table...
$('tr').each(function(){
var pTR = $(this);
// Skip the header row.
if (pTR.find('th').length == 0)
{
// This is the array of TDs in the given row.
var pCells = $('td', pTR);
retVal.push({state:$(pCells[0]).text(), place:$(pCells[1]).text(), county:$(pCells[2]).text()});
}
});
// retVal now contains an array of objects, including county.
if (retVal.length > 0)
{
alert(retVal[0].county);
}
else
{
alert('Cannot parse output page');
}
The parsing code is written to be extensible, hence you get back all of the data. With postal codes, although you will likely only ever get back one county, you'll definitely get back more places. Also note... not every zip code has a county attached for a variety of reasons, but you should get back an empty string in that case.

Categories

Resources